【问题标题】:What is the head Node of a linked lists? Is it the first Node or a reference to it?链表的头节点是什么?它是第一个节点还是对它的引用?
【发布时间】:2017-03-02 23:17:40
【问题描述】:

无法理解链表。这是在java中。我正在写一些方法,添加,删除,查找。但是在这里想知道的是,被定义为类型 Node 的 Head 是实际的第一个 Node 吗?它是否包含数据和下一个节点引用?还是它以某种方式告诉第一个数据是什么?

谢谢

【问题讨论】:

    标签: java linked-list


    【解决方案1】:

    head 节点是列表中的第一个节点。 tail 节点是列表中的最后一个节点。

    两者都没有什么特别之处。

    在您的LinkedList 类中,您可能引用了headtail,但节点本身只是节点。

    【讨论】:

      【解决方案2】:

      一般来说,不限于Java,所有列表节点都是一样的,“头”节点是列表中的第一个。这个“头”通常是一个变量,它是第一个列表节点的引用(或指针)。

      一个简单的单链表节点可能看起来像

      class ListNode
      {
          Object data;      // The data added to the list
          ListNode next;    // Reference to the next item in the list
      }
      

      那么“头”就是

      ListNode head;
      

      也就是说,一个名为“head”的变量保存(引用)一个ListNode。 这个问题在 Java 中有些混乱,因为所有东西(除了像 int 这样的原语)都是 reference — 所以这看起来像 "head is a ListNode" 而实际上是 “head 是对列表节点的引用”.

      从图形上看,如下所示,我将“数据”放在括号中并显示“下一个”指向某物。

      head -> ListNode("foo")next -> ListNode("bar")next -> ListNode("baz")next -> null
      

      next 持有null 值时,会找到列表的末尾。您还必须有一个ListNode tail;,它将被更新为指向添加到列表中的最后一个东西。

      这是一个非常简单(且未经测试)的概念示例。 Java 自己的java.util.LinkedList 要复杂得多,并且是用泛型参数化的。

      class List
      {
          ListNode head = null;
          ListNode tail = null;
      
          public add(Object o)
          {
              ListNode node = new ListNode(o);
              if (head == null) head = node;         // if there's no head yet this is the head
              if (tail != null) tail.next = node;    // if there's a tail point tail at this new node
              tail = node;                           // and this is the new tail
          }
          // need remove() etc other methods
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-16
        • 1970-01-01
        • 2011-05-23
        • 2022-08-16
        • 1970-01-01
        • 2014-10-12
        • 1970-01-01
        相关资源
        最近更新 更多