3

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
  • 1
    Unless you want retrieval by index or duplicates, I'd suggest you to use a SortedSet<Node> and Node implements Comparable<Node> instead. Commented May 2, 2010 at 20:50
  • @BalusC: I'm pretty sure this is a write-your-own X HW assignment, based on user69514 question history and the question itself. Which I suspect means real answers are out, though SortedSet<Integer> would probably suffice, since it seems that's all the data Node holds. Commented May 3, 2010 at 1:22

4 Answers 4

4

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

this look better, but it goes into an infinite loop
whoops, forgot to update the current reference at the end of the loop
2

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.

Comments

1

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

current = current.next;

Comments

0

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

Comments

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.