c++ - 如何在链表的节点之间移动?

标签 c++ list pointers linked-list

这是一段尝试构建链表的代码。

struct node {
    char name[20];
    int age;
    int height;
    node* next; // Pointer to the next node
};
node* startPTR = NULL;

void addNode_AT_END() {
    node *temp1;
    node *temp2;

    temp1 = new node;  

    cout << "Enter the name : ";
    cin  >> temp1->name;
    cout << endl << "Enter the age : ";
    cin  >> temp1->age;
    cout << endl << "Enter height : ";
    cin  >> temp1->height;

    temp1->next = NULL;

    if( startPTR == NULL) {
       startPTR = temp1; 
    }  else {
       temp2 = startPTR;

       while( temp2->next != NULL )
           temp2 = temp2->next;

       temp2->next = temp1;
    }
 }

下图是对上述函数进行 2 次背靠背调用后的示意图。

start = addr1;
|
V
(addr1) ----> (addr2) ----> (NULL)      at end
^
|
temp2

其中addr1和addr2分别是第一个和第二个节点的地址。

第三次调用后会发生什么?第三次调用的迭代将如何进行?我无法理解 list 在第二次调用后如何链接。据我所知,所有已经建立起来的知识都将消失. 那么榜单将如何走得更远呢?第三次调用时节点如何放置?

最佳答案

这里是所有魔法发生的地方:

1. temp2 = startPTR;
2. while( temp2->next != NULL )
3.    temp2 = temp2->next;
4. temp2->next = temp1;

首先,temp2 将指向列表的开头。在第 2 行和第 3 行中,将 temp2 更改为下一个节点,直到到达 temp2->nextNULL 的节点。该节点是列表的最后一个节点,与列表的大小无关。

最后,在第 4 行中,您将 temp2->next 更改为 temp1 因此现在它指向新节点(即最后一个节点现在指向新节点) . temp1->next 也是 NULL,因此 temp1 现在表示列表的末尾。

在第 1 行之后

start = addr1;
|
V
(addr1) ----> (addr2) ----> (NULL)
^
|
temp2

temp2->next 不是 NULL(它是 addr2),所以你迭代并执行第 3 行,你会得到:

start = addr1;
|
V
(addr1) ----> (addr2) ----> (NULL)
              ^
              |
              temp2

temp2->next 现在是 NULL。所以你停止循环并执行第 4 行,你会得到:

start = addr1;
|
V
(addr1) ----> (addr2) ----> (addr3) ----> (NULL)
              ^             ^
              |             |
              temp2         temp1

注意:你知道指针是如何工作的吗?想象一下:你有一个节点,它是内存中的一些数据。当内存中有变量时,这些变量就有地址。假设 addr1 为 10,addr2 为 150,addr3(刚刚 newed 的节点)为 60。start 的值为 10。因此,“指向”第一个列表的节点(即使用此地址,您可以访问其数据)。其中一个数据是 next 字段。第一个节点的 next 字段的值为 150,因此指向下一个节点。当你说 temp2 = start 时,你将数字 10 放入 temp2 中,此时 temp2->next 的值为 150。当你说 temp2=temp2->next,您只需将值 150 放入 temp2,覆盖之前的值。通过这种方式,您已经有效地将指针从指向第一个节点移动到现在指向第二个节点。现在 temp2->nextNULL(即 0)。当您现在说 temp2->next=temp1 时,您将值 60 放入 temp2next 字段中。所以现在 temp2->next 是 60。temp2->next->nextNULL

关于c++ - 如何在链表的节点之间移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262078/

相关文章:

c++ - 所有权应该在 STL 容器调用其值的析构函数之前还是之后结束?

c++ - 我如何在 void* 和 boost shared_ptr 之间进行转换

c++ - 指针转换是否保持对齐属性?

c - 为什么会出现取消引用指针错误?

c++ - 如何在 Visual C++ 6.0 中使用 NormalizeString()?

c++ - 解决友元类的循环依赖

Python 对象列表更新

r - 将数据框转换为列表,具有应用系列的功能

python - 字典列表中的问题

c - 复制一个指针,然后返回第一个有什么用