简体   繁体   中英

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:

#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. 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()?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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