在添加到链表时遇到问题,两个看似相同的代码给出了截然不同的结果

发布于 2025-01-14 00:35:13 字数 719 浏览 4 评论 0原文

我在这里尝试将一个节点添加到单链表中,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海少女心 2025-01-21 00:35:13

在您的第一个代码中,当 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 do head.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 to null. so now you are assigning head = s so head will point to newly created node and it is not appended to your original list.

空袭的梦i 2025-01-21 00:35:13

通过逐步调试应该很简单,我想这就是学习它的方法...尝试在 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)...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文