在添加到链表时遇到问题,两个看似相同的代码给出了截然不同的结果
我在这里尝试将一个节点添加到单链表中,
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head.next != null){
head = head.next;}
head.next = s;
return a;
}
这个可以工作,但是如果我这样做 -
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head != null){
head = head.next;}
head = s;
return a;
}
列表现在只包含一个节点
i am here trying to add a node to a singlylinkedlist
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head.next != null){
head = head.next;}
head.next = s;
return a;
}
this one works but if i do this -
SinglyLinkedListNode s = new SinglyLinkedListNode(data);
if(head == null){SinglyLinkedList a = new SinglyLinkedList();
a.head = s;
return a.head;}
else{
SinglyLinkedListNode a = head;
while(head != null){
head = head.next;}
head = s;
return a;
}
some how the list now contains only one node
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的第一个代码中,当
head.next != null
时,while 循环终止,终止后 head 将指向链表中的最后一个节点,当您执行head.next = s
时它将把新节点附加到您现有的列表中。在第二个代码中,当
head == null
时,while 循环终止,终止后 head 将指向null
。所以现在您正在分配 head = s ,因此 head 将指向新创建的节点,并且它不会附加到您的原始列表中。In your first code while loop terminates when
head.next != null
, after termination head will point to last node in the linked list and when you dohead.next = s
it will append new node to you existing list.In your second code while loop terminates when
head == null
, after termination head will point tonull
. so now you are assigninghead = s
so head will point to newly created node and it is not appended to your original list.通过逐步调试应该很简单,我想这就是学习它的方法...尝试在 while 循环和下一行处放置断点(直接将值分配给
head
),并检查变量的值(主要是 F8 键用于调试)...It should be very simple to find out with debugging step by step, and I guess that is way to learn it... try out putting break point at while loop and next line (assigning value directly to
head
), and check values of variables (mostly F8 key for debugging)...