views:

81

answers:

1

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 after = 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;
    }
}
+3  A: 

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.

SB
I support this strategy. I usually create a Node class and a List class. The node List class has all the logic to manage the list. The node class has only the information required to construct the list
rsarro
+1 composite pattern is not appropriate here. A tree is a good example for a composite pattern where one can treat ever node as a (sub)tree
Dave
I fixed it myself nonetheless
danutenshu