首页 > 解决方案 > 我可以以这种方式为链表实现 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* 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);
    }
}

但我想知道是否可以在另一个节点之后添加一个节点(我说的是这段代码,见下文):

    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() 的概念?

标签: c++pointersmemorysingly-linked-listpush-back

解决方案


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

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

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


推荐阅读