Adding Nodes to LinkeList

时间:2015-09-14 16:14:34

标签: java nodes

I am trying to make this method add a Node in the Linked List. The first part works and I am able to add a node in positions 2 and up. But when I try to add it to position 1(0), it fails.

public boolean add(double val, int pos)
{
   Node t = root;
   int count = 1;
   Node n = new Node();
   while(t != null)
   {
      if(pos-1 == count)
      {
           n.next = t.next;
           t.next = n;
      }
      else if(pos == 1)
      {
           n.next = t;
           t = n;
      }
      count++;
      t = t.next; 
    }
  return true;
}

1 个答案:

答案 0 :(得分:0)

Looks like you are trying to handle adding to front of list as an edge case by replacing the root, but you are not assigning the new node to the root, you are assigning it to the local variable t (which goes out of scope).

Try this change:

     ...
      else if(pos == 1)
      {
           n.next = t;
           root = n;//NOT t = n;
      }
     ...