0

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;
    }
}
2
  • 1
    You might want to look into using sentinel nodes to avoid needing special cases for the ends Commented Jul 19, 2010 at 22:03
  • Think about how much easier your list management would be if you always acted on the head node of a list rather than an arbitrary node. addToIndexAt in a List class that maintains a reference to the head could always walk the list, find the node to insert into, and then do the insert. It could even update the head pointer internally. Commented Jul 19, 2010 at 22:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
+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
I fixed it myself nonetheless

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.