Counter=Counter->nextptr 在链表中到底是如何工作的?

问题描述 投票:0回答:1

我刚刚开始使用 C++ 中的链接列表。我的问题很长,但如果有人能花时间回答我,我将不胜感激。

我的问题总结是,当

current->nextptr
在构造函数中指向
nextptr
时,
nullptr
如何获取节点?

#include <iostream>
using namespace std;

struct node
{
    int data;
    node *nextptr;

    node(int valueUinsert)
    {
        this->data = valueUinsert;
        nextptr = nullptr;
    }
};

void InsertAtEnd(node *&head, int valueUinsert)
{
    node *n = new node(valueUinsert);
    node *counter = head; 

    if (head == nullptr) 
    {
        head = n;
    }
    else
    {
        while (counter->nextptr != nullptr)
        {
            counter = counter->nextptr;
        }
        counter->nextptr = n;
    }
}

int main()
{
    node *head = nullptr;
    InsertAtEnd(head, 2);
    InsertAtEnd(head, 3);
}

我正在尝试理解这段代码。让我向您解释一下我的理解以及我的问题是什么。如果我有什么错误的地方,请指正。

首先,我创建一个

node
类,并在其构造函数中使用
int
值对其进行参数化,该值将由我作为我想要放入
data
中的
node
传递。在这个构造函数中,有一个名为
nextptr
的成员,它是一个指针,目前设置为
nullptr
,而
data
则设置为我要在
node
中添加的值。

然后,我在

node
函数中创建一个
head
类型的
main()
指针,它也指向
nullptr
。现在,为了在链接列表中添加元素,我创建了一个函数
InsertatEnd()
,它接受我在
node
中创建的真实
head
类型
main()
指针,以及我想要添加到的
int
值列表。

在函数中,我创建了另一个名为

node
n
类型指针,并为
node
类型对象动态分配堆上的内存,该对象接受我要添加到列表中的值,并将名为
node
node
类型指针中该
n
类型对象的地址。到目前为止我所说的一切都正确吗?

然后,我创建另一个名为

node
counter
类型指针,它指向
head
指针所指向的同一内存位置,即本例中的
nullptr
。然后,我检查列表是否为空,将传递的值存储在
head
中,否则遍历
counter
直到结束,以便我可以将传递的值放在末尾。

现在,这是我不理解代码/逻辑的地方。我不明白这个

counter->nextptr
是如何工作的。

while
循环中,我有条件运行此代码,直到
counter
指向
nullptr

假设我在

main()
中写道:

InsertAtEnd(head, 2);
InsertAtEnd(head, 3);

现在,当执行

InsertAtEnd(head, 2);
时,它会将值
2
赋予我们的
node
对象,这样
data
node
将存储值
2
,从而使
 n
指向
2
。我的说法对吗?

然后,在下一行中,它将使我们的

counter
指向与
head
相同的位置,然后当我到达
if
语句时,它将运行,因为我们的
head
指向
nullptr
现在,它将使我们的
head
指针指向与
n
相同的东西,即存储
node
作为其
2
data
对象。

然后,我回到

main()
函数并执行
InsertAtEnd(head, 3);

现在,它会再次将真正的

head
指针传递给函数,并将值
3
赋予我们的
node
对象,作为
data
node
。问题:是否应该覆盖之前的值(2)?

现在,直到这个阶段,

counter
都指向
nullptr
,这是
head
的先前值。但现在,我们的
counter
将指向我们的头所指向的
2

现在,它将跳过

if
语句并转到
else
。这是我不明白的地方。

else
语句中,我有一个
while
循环,它将遍历
counter
直到到达
nullptr
。现在,
counter->nextptr
是什么意思?现在
counter
是指向
2
的指针,
nextptr
是指向
nullptr
的指针,那么这个
counter->nextptr
是如何工作的呢?这对我来说毫无意义,它是如何遍历的?然后,在
while
循环体中,我们有这个:

counter = counter->nextptr;

这个

counter->nextptr
如何获取
counter
的下一个值?它是如何工作的?请解释一下。

我只是想了解这个

current->nextptr
是如何工作的。

c++ data-structures linked-list singly-linked-list dsa
1个回答
0
投票

简而言之,

head
指向列表中的第一个
node
,每个
node
nextptr
指向列表中的下一个
node
,其中最后一个
node
nextptr 
nullptr

  • main()
    中,您的
    head
    最初是
    nullptr

  • InsertAtEnd(head, 2)
    的第一次调用看到
    head
    nullptr
    ,因此它会更新
    head
    以指向新的
    node
    ,其
    data
    2
    nextptr
    nullptr

  • 第二次调用

    InsertAtEnd(head, 3)
    看到
    head
    不是
    nullptr
    ,因此它一次遍历列表1个
    node
    ,直到找到最后一个
    node
    ,其
    nextptr
    nullptr
    ,然后更新
    nextptr
    以指向新的
    node
    ,其
    data
    3
    nextptr
    nullptr

等等。

© www.soinside.com 2019 - 2024. All rights reserved.