Inserting at the end involves traversing the entire list until we reach the last node. We then set the last node's next reference to point to the new node, making the new node the last element in the list.
Following is the approach to add a new node at the end of the linked list:
Create a new node and set its next pointer as NULL since it will be the last node.
Store the head reference in a temporary variable
If the Linked List is empty, make the new node as the head and return
Else traverse till the last node
Change the next pointer of the last node to point to the new node
Below is the implementation of the approach:
C++
#include<iostream>usingnamespacestd;// A linked list nodeclassNode{public:intdata;Node*next;// Constructor to initialize a new node with dataNode(intx){data=x;next=nullptr;}};// Given the head of a list and an int, appends// a new node at the end and returns the head.Node*insertAtEnd(Node*head,intx){// Create a new nodeNode*newNode=newNode(x);// If the Linked List is empty, make// the new node as the head and returnif(head==nullptr){returnnewNode;}// Store the head reference in a temporary variableNode*last=head;// Traverse till the last nodewhile(last->next!=nullptr){last=last->next;}// Change the next pointer of the last node // to point to the new nodelast->next=newNode;// Return the head of the listreturnhead;}// This function prints the contents // of the linked list starting from the headvoidprintList(Node*node){while(node!=nullptr){cout<<node->data;if(node->next!=nullptr){cout<<" -> ";}node=node->next;}cout<<endl;}intmain(){// Create a linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head=insertAtEnd(head,6);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>// Define a linked list nodestructNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}// Function to insert a new node at the end of the liststructNode*insertAtEnd(structNode*head,intx){structNode*newNode=createNode(x);// If the list is empty, return the new node as headif(head==NULL)returnnewNode;// Traverse to the last nodestructNode*last=head;while(last->next!=NULL){last=last->next;}// Link the last node to the new nodelast->next=newNode;returnhead;}// Function to print the linked listvoidprintList(structNode*node){while(node!=NULL){printf("%d",node->data);if(node->next!=NULL)printf(" -> ");node=node->next;}printf("\n");}intmain(){// Create a linked list: 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);// Insert a new node at the endhead=insertAtEnd(head,6);// Print the linked listprintList(head);return0;}
Java
// A linked list nodeclassNode{intdata;Nodenext;// Constructor to initialize a new node with dataNode(intx){data=x;next=null;}}classGfG{// Given the head of a list and an int, appends// a new node at the end and returns the head.staticNodeinsertAtEnd(Nodehead,intx){// Create a new nodeNodenewNode=newNode(x);// If the Linked List is empty, make// the new node as the head and returnif(head==null){returnnewNode;}// Store the head reference in a temporary variableNodelast=head;// Traverse till the last nodewhile(last.next!=null){last=last.next;}// Change the next pointer of the last node // to point to the new nodelast.next=newNode;// Return the head of the listreturnhead;}// This function prints the contents // of the linked list starting from the headstaticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null){System.out.print(" -> ");}node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a linked list:// 1 -> 2 -> 3 -> 4 -> 5 Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=insertAtEnd(head,6);printList(head);}}
Python
# A linked list nodeclassNode:def__init__(self,x):# Constructor to initialize a new node with dataself.data=xself.next=None# Given the head of a list and an int, appends# a new node at the end and returns the head.definsertAtEnd(head,x):# Create a new nodenewNode=Node(x)# If the Linked List is empty, make# the new node as the head and returnifheadisNone:returnnewNode# Store the head reference in a temporary variablelast=head# Traverse till the last nodewhilelast.nextisnotNone:last=last.next# Change the next pointer of the last node # to point to the new nodelast.next=newNode# Return the head of the listreturnhead# This function prints the contents # of the linked list starting from the headdefprintList(node):whilenodeisnotNone:print(node.data,end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":# Create a linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head=insertAtEnd(head,6)printList(head)
C#
usingSystem;// A linked list nodeclassNode{publicintdata;publicNodenext;// Constructor to initialize a new node with datapublicNode(intx){data=x;next=null;}}classGfG{// Given the head of a list and an int, appends// a new node at the end and returns the head.staticNodeinsertAtEnd(Nodehead,intx){// Create a new nodeNodenewNode=newNode(x);// If the Linked List is empty, make// the new node as the head and returnif(head==null){returnnewNode;}// Store the head reference in a temporary variableNodelast=head;// Traverse till the last nodewhile(last.next!=null){last=last.next;}// Change the next pointer of the last node // to point to the new nodelast.next=newNode;// Return the head of the listreturnhead;}// This function prints the contents // of the linked list starting from the headstaticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data);if(node.next!=null){Console.Write(" -> ");}node=node.next;}Console.WriteLine();}staticvoidMain(string[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5 Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=insertAtEnd(head,6);printList(head);}}
JavaScript
// A linked list nodeclassNode{constructor(x){// Constructor to initialize a new node with datathis.data=x;this.next=null;}}// Given the head of a list and an int, appends// a new node at the end and returns the head.functioninsertAtEnd(head,x){// Create a new nodeletnewNode=newNode(x);// If the Linked List is empty, make// the new node as the head and returnif(head===null){returnnewNode;}// Store the head reference in a temporary variableletlast=head;// Traverse till the last nodewhile(last.next!==null){last=last.next;}// Change the next pointer of the last node // to point to the new nodelast.next=newNode;// Return the head of the listreturnhead;}// This function prints the contents // of the linked list starting from the headfunctionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.next!==null){process.stdout.write(" -> ");}node=node.next;}console.log();}// Driver codefunctionmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=insertAtEnd(head,6);printList(head);}main();
Output
1 -> 2 -> 3 -> 4 -> 5 -> 6
Time Complexity: O(n) where nis the length of the linked list Auxiliary Space: O(1)