Reputation: 51
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()?
Upvotes: 1
Views: 1001
Reputation: 63019
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.
Upvotes: 2