Inserting a node at the end of a linked list
In our previous article we learned how to insert a node at the beginning of a linked list. In this article we will see how we can insert a node at the end of the linked list.
Approach:
Declare head pointer and make it as NULL.
Create a new node with the given data. And make the new node => next as NULL. We have to do this because the new node is going to be the last node.
If the head node is NULL (Empty Linked List), make the new node as the head.
If the head node is not NULL, i.e Linked list already has some elements, find the last node. Make the last node => next as the new node.
Example:
If this linked list looks like: 5->10->15->NULL.
And if you want to insert 20,
after insertion at end it will look like: 5->10->15->20->NULL.
Code:
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
Node()
{
this->next = NULL;
}
};
void traverseLinkedList(Node *node)
{
while(node!=NULL)
{
cout<<node->data<<", ";
node = node->next;
}
}
void insertAtEnd(int data, Node * &head)
{
Node *node = head;
Node *newNode = new Node();
newNode->data = data;
while(node->next!=NULL)
{
node = node->next;
}
node->next = newNode;
}
int main()
{
Node *head = new Node();
head->data = 5;
Node *first = new Node();
first->data = 10;
Node *last = new Node();
last->data = 15;
head->next = first;
first->next = last;
cout<<"Before Insertion: ";
traverseLinkedList(head);
insertAtEnd(20, head);
cout<<"\nAfter Insertion: ";
traverseLinkedList(head);
return 0;
}
Output:
Before Insertion: 5, 10, 15,
After Insertion: 5, 10, 15, 20,
This is how you insert a node at the end of the linked list.