简体   繁体   English

我可以以这种方式为链表实现 push_back 方法吗?

[英]Can I implement a push_back method for linked list in that way?

I've already been doing push_back methods for link lists like that:我已经为这样的链接列表做 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);
    }
}

But I wonder if I could add a node after another one (I am talking about this piece of code see below):但我想知道是否可以在另一个节点之后添加一个节点(我说的是这段代码,见下文):

    else{
        Node *current = head;
        while(current->next != nullptr){
            current = current->next;
        }
        current->next = new Node(data);
    }

Not using the condition:不使用条件:

while(current->next != nullptr)
{current = current->next;}

,but instead doing: ,而是做:

while(current != nullptr){current = current->next;}

When doing that we equalize the current pointer to a nullptr.这样做时,我们将当前指针均衡为一个 nullptr。 Is it possible from that point to add a new Node at the end and linking that Node to the whole list?从那时起是否可以在末尾添加一个新节点并将该节点链接到整个列表?

Or the concept of while(current != nullptr) is not favorable for push_back()?还是while(current != nullptr)的概念不利于 push_back()?

You could do something like that, by taking a pointer to the pointer you wish to change.您可以通过将指针指向您希望更改的指针来执行类似的操作。

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

As a bonus, you don't have a special case for empty lists anymore.作为奖励,您不再有空列表的特殊情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM