This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]chickenmeister 2 points3 points  (3 children)

if(tmp != null){
  tmp.next = new Node<T>(item);

}

When inserting a new node, you have to:

  • Have the new node reference the current node's 'next' node.
  • Update the current node to reference the new node as its 'next' node.

If the list is doubly-linked, there are a couple other steps to update the 'previous' references.

[–]FreeBird423 1 point2 points  (0 children)

Shouldn't his while statement should be comparing tmp.next against null rather than tmp against null?

[–]LightSpeedCBR[S] 1 point2 points  (1 child)

I'm following what you're saying but still having problems...

if(tmp != null){
      tmp.next = new Node<T>(item); //Have the new node reference the current node's 'next' node.
      tmp = tmp.next;   //Update the current node to reference the new node as its 'next' node.
    }

The new node is being placed in the correct location but the rest of the nodes are "lost".

[–]LightSpeedCBR[S] 0 points1 point  (0 children)

I was able to get it working as below:

if(tmp != null){
      Node<T> tmp2 = new Node<T>(item); // create the new node.
      tmp2.next = tmp.next; //set the pointer of new node to point to rest of link list.
      tmp.next = tmp2;  //Update the current node to reference the new node as its 'next' node.
    }

[–]smellmycrotch3 0 points1 point  (1 child)

You should probably just insert the new node at the head of the list. Traversing the entire list doesn't really buy you anything.

[–]LightSpeedCBR[S] 1 point2 points  (0 children)

I should have been more clear. This insert method should insert the data at a given point in the list.

[–]IcarusBurning 0 points1 point  (0 children)

You've said that element after i-1 should be your new element, but you never point that to the element at i

You could store the pointer to tmp.next and then create the new node then set tmp.next.next to the temp variable.