澄清链表节点

时间:2013-09-09 14:02:27

标签: c++ data-structures

我试图了解链表节点是什么。什么传递给构造函数?特别是什么节点*头?它是指向结构本身的指针。链接列表如何适应这种结构?

struct node {
    node* next;
    int data;
    explicit node(int data) : node(nullptr, data) {}
    node(node* head, int data) : next(head), data(data) {}
}

EDIT ::

我的问题应该更清楚。我知道我可以手动定义每个节点并初始化它们并继续这样做以创建列表。但是如何从节点实现列表而不指定每次我想要的内容?我想我得到的是我不确定如何从给定节点定义的节点构建列表。

5 个答案:

答案 0 :(得分:1)

让我们首先关注单个节点:

--------
| data |
--------
| next |
--------

显然,data成员保存当前节点的数据。因此,node只是data持有者对,以及指向列表中下一个元素的指针(next)。现在,名称“链接”列表告诉您这种数据结构是通过某些链接连接的。所以你可能有多个链接在一起的节点,如下所示:

--------     --------       --------
| 5    |     | 3    |     | 6       |
--------     --------      --------
| next | --->| next | --->| nullptr |
--------     --------      --------

很容易找到哪个节点是列表中的最后一个节点 - 它是next指针的值为nullpointer的节点,表明没有更多的节点清单。

但是,我们将如何找到列表的第一个元素?我们将通过将head指针 - 指针指向内存中某个位置的列表的第一个元素来实现这一点:

--------     --------       --------
| 5    |     | 3    |     | 6       |
--------     --------      --------
| next | --->| next | --->| nullptr |
--------     --------      --------

  ^
  |
 head

通过存储head指针,我们可以像这样轻松遍历列表:

node *tmp = head; // tmp is our "iterator" through the list
while(tmp != nullptr) 
{
   // Print the data
   cout << tmp->data;

   // Move iterator to the next element
   // Note that when we print the last element,
   // tmp will become nullptr, and the loop will break!
   tmp = tmp->next;
}
  

我的问题应该更清楚。我知道我可以手动定义每个节点并初始化它们并继续这样做以创建列表。但是如何从节点实现列表而不指定每次我想要的内容?我想我得到的是我不确定如何从给定节点定义的节点构建列表。

有一个聪明的诀窍 - 你可以将last指针放在某处,你可以创建一个辅助函数,例如:

void insert(int data)
{
    node* n = new node(data);

    // If the list is empty:
    if(head == nullptr)
    {
       // This element becomes the first!
       head = n;
    }
    else
    {
       // Append this element to the end of the
       // list
       last->next = n;
    }

    // Update last, as this is the last
    // element in the list
    last = n;
}

答案 1 :(得分:0)

node* head是您node的第一个实例,您显然已将其保留为引用/句柄。后续实例化形成链表。

答案 2 :(得分:0)

链接列表是一系列连接在一起的东西。列表中的每个东西都是(或由其保存)“节点”,因此链表节点是链表中的条目。在示例中,您给节点是一个结构,其中包含值(“数据”)的空间以及指向下一个列表节点的指针的空间。

示例中的第一个构造函数初始化节点但不将其链接到列表中。 第二个创建一个节点并使其成为列表的头部。您的列表是通过将新节点推到头上而构建的。头部是列表中的第一个节点,所有其他节点都可以通过从头部开始跟随“下一个”指针来到达。

答案 3 :(得分:0)

Linked-list节点实际上是Linked-list的一个节点,它有数据字段和指向下一个节点的指针。就像你的代码已经显示的那样。

struct node {
    node* next;
    int data;
    explicit node(int data) : node(nullptr, data) {}
    node(node* head, int data) : next(head), data(data) {}
}

node *head如果被放入链表结构中则更清楚,这使得链表操作更方便。例如:

struct linkedlist {
   node *head;
   linkedlist();
   node *getHead();
   node *getNext();
   void traverse_list();
   ......
}

答案 4 :(得分:0)

也许维基百科有助于澄清问题: http://en.wikipedia.org/wiki/Linked_list#Basic_concepts_and_nomenclature

命名法说:头是第一个元素,而尾是指其余元素。

相关问题