本文介绍了java链表数据插入在第N个位置.为什么函数insertN()不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Link{
    public  String val;
    public  Link nextlink;
    public Link(String val) {
        this.val = val;
    }
    public void linkNext(Link l){
        this.nextlink=l;
    }
    public void printlink()
    {
        System.out.print(" "+val);
   }
}
class linkList{
    Link first;
    public static int  count=0;
    public linkList(){
        first=null;
    }
    boolean isEmpty(){
        return first==null;
    }

    public void insertfirst(String str){

        Link next=new Link(str);
       count++;
       next.nextlink=first;
        first=next;
    }
    public void insertN(int pos,String str){
        if(pos<count){

         Link temp=first;
       count++;
       for(int i=0;i<pos-1;i++)
           temp=temp.nextlink;
       Link next=new Link(str);
     
       next=temp.nextlink;
         temp=next;
        }
    }
    public void printList(){
        Link currentLink=first;
      System.out.println("data is:");
        while(currentLink!=null){
            
            currentLink.printlink();
            currentLink=currentLink.nextlink;

    }
        System.out.println("  ");


}
}


public class LinkedList2 {
    public static void main(String[] args) {
        linkList li=new linkList();
        li.insertfirst("neeraj");
        li.insertfirst("rohit");
        li.insertfirst("lalit");
        li.insertfirst("meenu");
        li.printList();
        li.insertfirst("newly");
        li.insertN(9, "newlaay");
        li.printList();
        System.out.println(li.count);
    }

}

推荐答案

public void insertFirst(String str) {
    Link next = new Link(str);
    count++;
    next.setNextLink(first);
    first=next;
}



5.
insertN将无法按计划工作.允许Link类为您完成工作:



5.
insertN will not work as planned. Allow the Link class to do the work for you :

class Link
    // stuff

    Link getLink (int position) {
        if (position <= 0 || this.nextlink == null) {
            return this.nextLink;
        }
        else
        {
            return this.nextlink.getLink(position - 1);
        }
    }
}



然后在位置后添加:



Then to add after a position:

public void insertAfter(int pos,String str){
    Link previous = this.first.getLink(pos);
    if (previous != null) {
        Link next = previous.getNextLink();
        Link insert = new Link(str);
        previous.setNextLink(insert);
        insert.setNextLink(next);
    }
}



简单且减少错误的代码.



Simple and less code to go wrong.


这篇关于java链表数据插入在第N个位置.为什么函数insertN()不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 17:46