[英]Inserting a node in a pre sorted linked list
我一直在浏览关于黑客排名的Linkedlist问题,我目前正在解决这个问题,它会要求你在一个有序的双链表中插入一个节点。
这是我用Java编写的逻辑
Node SortedInsert(Node head,int data) {
Node newNode = new Node();
Node temp = head;
newNode.data = data;
newNode.next = null;
newNode.prev = null;
if(head == null){
head = newNode;
}else{
while(data > temp.data && temp.next != null){
temp = temp.next;
}
if(temp == head){
newNode.next = temp;
temp.prev = newNode;
head = newNode;
}else if(data > temp.data){
newNode.prev = temp;
temp.next = newNode;
}else{
newNode.prev = temp.prev;
newNode.next = temp;
temp.prev.next = newNode;
temp.prev = newNode;
}
}
return head;
}
这是我得到的错误。
Your Output (stdout)
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function.
2. There is a problem with your logic
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function.
2. There is a problem with your logic
我不知道我做错了什么。 我真的想知道我哪里出错了。 我知道很容易在网上找到答案,但我想如果有人能纠正我的错误,我会学到最好的。
问题是你总是在第一个元素之前插入第二个元素。 请考虑以下插图:
让链表最初为空。 现在,您按照算法插入1
。 head == null
情况被触发, head
现在指向newNode
。
x<-1->x
|
HEAD
现在,您尝试在列表中插入2
。 你会看到while
循环结束, temp
现在指向head
,触发后面的if条件( if(temp == head)
)。
x<-1->x
|
HEAD, temp
这会在 temp
之前插入2
(错误!)
x<-2<=>1->x
|
HEAD
交换条件的顺序应该解决问题:
if(data > temp.data) { // First, check if you need to insert at the end.
newNode.prev = temp;
temp.next = newNode;
} else if(temp == head) { // Then, check if you need to insert before head.
newNode.next = temp;
temp.prev = newNode;
head = newNode;
} else { // Otherwise, insert somewhere in the middle.
newNode.prev = temp.prev;
newNode.next = temp;
temp.prev.next = newNode;
temp.prev = newNode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.