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;
如果有人能一步一步地告诉我这些表达式是如何求值的,那就太好了。
编辑::
如何:
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
在列表中前进的方式:
更多问题
为什么我们必须取消引用指针才能访问下一个指针甚至数据本身?
你不必。
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
访问Head
的next成员。当然,这会计算出 another_node
的地址。
关于C++ 链表迭代成员访问运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255747/