链表.按顺序插入整数 [英] Linked List. Insert integers in order
本文介绍了链表.按顺序插入整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数链接列表.当我插入一个新节点时,我不需要将其插入到末尾,而是插入到其他节点中,例如2、4、5、8、11、12、33、55、58、102等.我不认为我将其插入正确的位置.看到我在做什么错了吗?
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;
}
}
推荐答案
我认为这可能更接近您的需求.
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;
}
}
这篇关于链表.按顺序插入整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文