Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以用这种方式实现链表的push_-back方法吗?_C++_Pointers_Memory_Singly Linked List_Push Back - Fatal编程技术网

C++ 我可以用这种方式实现链表的push_-back方法吗?

C++ 我可以用这种方式实现链表的push_-back方法吗?,c++,pointers,memory,singly-linked-list,push-back,C++,Pointers,Memory,Singly Linked List,Push Back,我已经在为链接列表使用push_-back方法,如下所示: #include <iostream> using namespace std; class Node{ public: int data; Node* next; Node(int data, Node* next = nullptr){ this->data = data; this->next = next; } }; Node* hea

我已经在为链接列表使用push_-back方法,如下所示:

#include <iostream>
using namespace std;

class Node{
public:
    int data;
    Node* next;
    Node(int data,
 Node* next = nullptr){
        this->data = data;
        this->next = next;
    }
};

Node* head = nullptr;

void push_back(int data){
    if(head == nullptr){
        head = new Node(data);
    }
    else{
        Node *current = head;
        while(current->next != nullptr){
            current = current->next;
        }
        current->next = new Node(data);
    }
}
不使用条件:

while(current->next != nullptr)
{current = current->next;}
,而是做:

while(current != nullptr){current = current->next;}
当这样做时,我们将当前指针均衡到一个nullptr。从那时起,是否可以在末尾添加一个新节点并将该节点链接到整个列表

或者是
while(current!=nullptr)

不利于push_back()?

您可以通过将指针指向您希望更改的指针来执行类似操作

void push_back(int data){
    Node** current = &head;
    while(*current != nullptr) { current = &(*current)->next; }
    *current = new Node(data);
}

作为奖励,您不再有空列表的特殊情况。

在当前实现中(
current->next!=nullptr
current
将在循环后指向列表的尾部。根据您建议的更改,
current
将在循环后成为
nullptr
。@Yksisarvinen进入nullptr是否意味着我们已经失去了与列表的连接?没错。你的目标是得到一个指向尾部(最后一个节点)的指针,如果你只检查
current
中的
nullptr
,你将越过尾部一步,而你无法从
nullptr
返回到任何有意义的地方。因此,你要跟踪指针的地址,即使在该地址是一个nullptr,您可以使用实际等于nullptr的指针地址分配内存。我说得对吗?是的,我们正在分配一个空的
节点*
current
始终指向
节点*
,它从不为空。非常感谢。现在我更准确地理解了在哪里可以使用双指针)
void push_back(int data){
    Node** current = &head;
    while(*current != nullptr) { current = &(*current)->next; }
    *current = new Node(data);
}