Linked List. Insert integers in order
I have a linked list of integers. When I insert a new Node I need to inser开发者_开发问答t 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;
}
}
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;
}
}
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.
It doesn't look like you're updating current
... try inserting something like this in your loop:
current = current.next;
Looks like you missing the case, when the new element is lesser than all existing ones.
精彩评论