Linked List. Insert integers in order

I have a linked list of integers. When I insert a new Node, I need to insert it not at the end, but at the other ... i.e. 2, 4, 5, 8, 11, 12, 33, 55, 58, 102, etc. I think I'm putting it in the right position. See what I'm 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;
            }
        }
+3
source share
4 answers

I think this may 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;
  }
}
+4
source

You never move forward on a list. you need another that sets:

current = current.next

You can also add a break statement after you have inserted node, because at this point you will end the loop.

+2
source

, current... - :

current = current.next;
+1

It seems that you are missing the case when the new item is smaller than all existing ones.

0
source

Source: https://habr.com/ru/post/1743739/


All Articles