Java – link 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 ord... I.e. 2,4,5,8,11,12,33,55,58102, etc. I don't think I insert it in the correct position Look what I did 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;
            }
        }

Solution

I think it's probably closer to what you're 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;
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>