C++ 链表迭代成员访问运算符

标签 c++ linked-list iteration

Node<T> *ptr = Head;
while (ptr)
{
T n = ptr -> data;
ptr = ptr -> next;
}

ptr = current index pointer,
next = linked list pointers,
data = node data.

我知道它正在遍历链表的指针和值。但我不明白的是,这些是如何工作的:

ptr -> data;
ptr -> next;

如果有人能一步一步地告诉我这些表达式是如何求值的,那就太好了。

编辑::

enter image description here

如何:

head->next;

得到地址 2200 的评估。我不明白 (*head).next 在没有被 head 指向时如何可以 = 2200。除非 data 和 next 共享相同的地址?我相当肯定这是错误的。

最佳答案

Node 的主要成员有:

1 - 指向另一个节点的指针。 (ptr,在您的示例中)

2 - 它保存的数据值。 (数据,在您的示例中)

Head 代表列表中的第一个节点。

所以,

Node<T> *ptr = Head;    // ptr points the ftrst node in the list.
while (ptr)             // the last node points nowhere (NULL), so if ptr is NULL we hit the end of the list.
{
T n = ptr -> data;      // This no need explanation.
ptr = ptr -> next;      // now we want to ptr point to the node is pointing its `next` pointer.
}  

这就是指针 ptr 在列表中前进的方式:

Describe how the pointer <code>ptr</code> advances through the list

更多问题

为什么我们必须取消引用指针才能访问下一个指针甚至数据本身?

你不必。

ptr->data;  // data is a member in a struct/class POINTED by ptr.
*ptr;       // this is the class/struct INSTANCE (dereferenced). So
*ptr.data;  // data is a member of that instance.

如果你有:

节点a; 节点 *ptr = &a; //以下是相同的: a.下一个; ptr->下一个; *ptr.next;

此外,由于 ptr 将指向数据,您可以取消引用它以获取数据的实际值。对吗?

不,ptr 永远不会指向数据(根据示例代码)。

ptr->data;  // This not means ptr will POINT to data.
            // this means "access to the data member of whatever object being POINTED by ptr".

根据给定的代码,ptr 实际上会指向链表中的每个成员?

是的,你明白了!

ptr->next 如何计算为下一个节点的地址?

指针也是一个变量。 int 变量保存 int 值,指针保存地址

一个非常简单(且无用)的节点应该是这样的:

struct Node {
    Node *next;   // Pointer to another node, yeah but ... which node? In a minute ;)
};

在某些时候,您将不得不编写如下代码:

// Example of adding a node.
Node* Head = new Node;
Node* another_node = new Node;
Head->next = another_node;  // This is how Head->next "knows" which node is the next. Because we told him.

所以,现在如果我们用另一个指针指向 Head 的相同地址,假设 ptr ...

Node *ptr = Head;

然后我们可以通过ptr->next访问Headnext成员。当然,这会计算出 another_node 的地址。

关于C++ 链表迭代成员访问运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255747/

相关文章:

c++ - 如何迭代 vector C++ 中的特定元素?

c++ - gcovr 排除问题

java - 如何打印链表中的内部节点?

c - 递归算法计算小于给定值的节点

java - HashMap 上的双重迭代具有对称结果(跳过冗余情况)

javascript - jQuery eq() 导致无限迭代

c++ - 准确评估 1/1 + 1/2 + ... 1/n 行

c++ - Windows上的封包记录

c++ - 如何在 C++ 中实现基本的 Variant(以及 Variant 上的访问者)模板?

java - 从链接列表中选择某些字符串