I am trying to figure out the following code to implement a push_back
function for a linked list but I'm not quite sure why we need back_ptr->next
and back_ptr
to both point to p
. I believe back_ptr->next
could just point to NULL
for it work, is there any advantage of implementing it as such that I'm missing?
void LinkedList::push_back(int element) {
Node *p = new Node;
p->element = elememt;
p->next = 0;
if (empty()) {
front_ptr = back_ptr = p;
} else {
back_ptr->next = p;
back_ptr = p;
}
}
The following is the LinkedList
class prototype. The back_ptr
is being used to point to the end of the list for implementing the copy constructor (push_back
makes it a lot easier to copy the list).
class LinkedList {
void push_back(int element);
// other member functions
private:
struct Node {
Node *next;
int element;
};
Node *front_ptr;
Node *back_ptr;
};