链表的头节点是什么?它是第一个节点还是对它的引用?

时间:2017-03-02 23:17:40

标签: java linked-list

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

由于

2 个答案:

答案 0 :(得分:1)

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

其中任何一个都没什么特别的。

LinkedList课程中,您可能会引用headtail,但节点本身只是节点。

答案 1 :(得分:0)

Generally, not limited to Java, all list nodes are the same, and the "head" node is the first one on the list. This, "head", is usually a variable that is a reference (or a pointer) to the first list node.

A simple singly-linked-list node may look like

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

Then "head" would just be

ListNode head;

that is, a variable named "head" that holds (a reference to) a ListNode. The issue gets somewhat confused in Java because everything (except primitives like int) is a reference — so this looks like "head is a ListNode" when it's actually "head is a reference to a list node".

Pictorially, this is like the following, where I've put the "data" in parens and show "next" pointing to something.

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

The end of the list is found when next holds the null value. You would have to also have a ListNode tail; which would be updated to point to the last thing added to the list.

Here's an extremely simple (and untested) example of the concepts. Java's own java.util.LinkedList is much more complicated, and is parameterized with generics.

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
}