views:

208

answers:

4

I have a linked list of integers. When I insert a new Node I need to insert it not at the end, but in oder... i.e. 2, 4, 5, 8, 11, 12, 33, 55, 58, 102, etc. I don't think I am inserting it in the correct position. Do see what Im doing wrong?

 Node newNode = new Node(someInt);
 Node current = head;

        for(int i=0; i<count; i++){
            if(current == tail && tail.data < someInt){
                tail.next = newNode;
            }   
            if(current.data < someInt && current.next.data >= someInt){
                newNode.next = current.next;
                current.next = newNode;
            }
        }
+2  A: 

You're never moving forward in the list. you need an else that sets:

current = current.next

You can also add a break statement after you've inserted the node since at that point you're done with the loop.

McAden
+1  A: 

It doesn't look like you're updating current... try inserting something like this in your loop:

current = current.next;
yjerem
+1  A: 

I think this might be closer to what you are looking for.

Node newNode = new Node(someInt);
Node current = head;
//check head first
if (current.data > newNode.data) {
  newNode.next = head;
  head = newNode;
}

//check body
else {
  while(true){
    if(current == tail){
      current.next = newNode;
      tail = newNode;
      break;
    }   
    if(current.data < someInt && current.next.data >= someInt){
      newNode.next = current.next;
      current.next = newNode;
      break;
    }
    current = current.next;
  }
}
Chris J
this look better, but it goes into an infinite loop
whoops, forgot to update the current reference at the end of the loop
Chris J
A: 

Looks like you missing the case, when the new element is lesser than all existing ones.

Dominik