1

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

dimm
  • 51
  • 1
  • 7
  • In your current implementation (`current->next != nullptr`) `current` will point to tail of the list after loop. With your proposed change, `current` will be `nullptr` after the loop. – Yksisarvinen Jul 28 '20 at 10:53
  • @Yksisarvinen getting into a nullptr does mean that we've already lost the connection with the list? – dimm Jul 28 '20 at 10:56
  • That's right. Your goal is to get a pointer to tail (last node), if you only check `current` for `nullptr` you will go one past the tail and you cannot go back from `nullptr` to anything meaningful. – Yksisarvinen Jul 28 '20 at 10:59

1 Answers1

2

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.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • so you're keeping track of addresses of pointers, that even if at that address is a nullptr, you can alloc memory using the address of the pointer that actually is equal to nullptr. Am I getting this right? – dimm Jul 28 '20 at 12:11
  • Yes, we are assigning to a `Node *` that is null. `current` always points to a `Node *`, it is never null. – Caleth Jul 28 '20 at 12:14
  • Thanks a lot. Now I got a more accurate understanding of where I could use double pointers) – dimm Jul 28 '20 at 12:18