开发者

How to add to beginning of a linked list in Java

开发者 https://www.devze.com 2023-01-08 12:13 出处:网络
I am creating a linked list function for homework that adds at any index except last, but I don\'t understand how to make a conditiontargetList.addToIndexAt(81,0); without sentinel nodes

I am creating a linked list function for homework that adds at any index except last, but I don't understand how to make a conditiontargetList.addToIndexAt(81,0); without sentinel nodes

EDIT Okay, I fixed all of the problems, except for one. This time, the code runs the code states that the result is 81,0,0,0,0, which means that after returns back to 0 every cycle of the code. How do i make the after=after.tail retain it's number?

public void addToIndexAt(int n, int index){
    IntList addition = new IntList(n);
    if(index==0){  //THIS IS MY PROBLEM
            IntList beginning=this;
        IntList after=this;
        IntList current=this;
        IntList temp=this;
        while(after.tail!=null){
            after=after.tail;
            temp=after;
            after.head=current.head;
        }
        beginning.head=n;
    }
    else{
        IntList af开发者_Go百科ter = this;
        IntList before = this;
        int nafter = index;
        int nbefore = index;
        while(nafter>0){
            after = after.tail;
            nafter--;
            }
        addition.tail = after; 
        while(nbefore>1){
            before = before.tail;
            nbefore--;
            }
        before.tail= addition;
    }
}


It seems you are treating the Node class the same as a List class. To me, these are different. I would suggest creating a class called List that holds a reference to the first node in the list.

Alternatively, you can try changing your code slightly where the insert method returns the new head of the list.

0

精彩评论

暂无评论...
验证码 换一张
取 消