Insertion in Linked List
Last Updated :
08 Aug, 2024
Given a Linked List, the task is to insert a new node in this given Linked List at the following positions:
- At the front of the linked list
- After a given node.
- At a specific position.
- At the end of the linked list.
To insert a new node at the front, we create a new node and point its next reference to the current head of the linked list. Then, we update the head to be this new node. This operation is efficient because it only requires adjusting a few pointers.

Insert a Node at the Front/Beginning of Linked List
Algorithm:
- Make the first node of Linked List linked to the new node
- Remove the head from the original first node of Linked List
- Make the new node as the Head of the Linked List.
Below is the implementation of the approach:
C++
// C++ Program to insert the node at the beginning of
// Linked List
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int new_data)
{
data = new_data;
next = nullptr;
}
};
// Function to insert a new node at the beginning of the
// list
Node* insertAtFront(Node* head, int new_data)
{
// Create a new node with the given data
Node* new_node = new Node(new_data);
// Make the next of the new node point to the current
// head
new_node->next = head;
// Return the new node as the new head of the list
return new_node;
}
void printList(Node* head)
{
// Start from the head of the list
Node* curr = head;
// Traverse the list
while (curr != nullptr) {
// Print the current node's data
cout << " " << curr->data;
// Move to the next node
curr = curr->next;
}
// Print a newline at the end
cout << endl;
}
int main()
{
// Create the linked list 2->3->4->5
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(5);
// Print the original list
cout << "Original Linked List:";
printList(head);
// Insert a new node at the front of the list
cout << "After inserting Nodes at the front:";
int data = 1;
head = insertAtFront(head, data);
// Print the updated list
printList(head);
return 0;
}
C
// C Program to insert the node at the beginning of
// Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with the given data
struct Node* createNode(int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node at the beginning of the
// list
struct Node* insertAtFront(struct Node* head, int new_data)
{
// Create a new node with the given data
struct Node* new_node = createNode(new_data);
// Make the next of the new node point to the current
// head
new_node->next = head;
// Return the new node as the new head of the list
return new_node;
}
void printList(struct Node* head)
{
struct Node* curr = head;
while (curr != NULL) {
printf(" %d", curr->data);
curr = curr->next;
}
printf("\n");
}
int main()
{
// Create the linked list 2->3->4->5
struct Node* head = createNode(2);
head->next = createNode(3);
head->next->next = createNode(4);
head->next->next->next = createNode(5);
// Print the original list
printf("Original Linked List:");
printList(head);
// Insert a new node at the front of the list
printf("After inserting Nodes at the front:");
int data = 1;
head = insertAtFront(head, data);
// Print the updated list
printList(head);
return 0;
}
Java
// Java Program to insert the node at the beginning of
// Linked List
class Node {
int data;
Node next;
Node(int new_data)
{
data = new_data;
next = null;
}
}
public class GFG {
// Function to insert a new node at the beginning of the
// list
public static Node insertAtFront(Node head,
int new_data)
{
// Create a new node with the given data
Node new_node = new Node(new_data);
// Make the next of the new node point to the
// current head
new_node.next = head;
// Return the new node as the new head of the list
return new_node;
}
public static void printList(Node head)
{
Node curr = head;
while (curr != null) {
System.out.print(" " + curr.data);
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args)
{
// Create the linked list 2->3->4->5
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
// Print the original list
System.out.println("Original Linked List:");
printList(head);
// Insert a new node at the front of the list
System.out.println(
"After inserting Nodes at the front:");
int data = 1;
head = insertAtFront(head, data);
// Print the updated list
printList(head);
}
}
Python
# Python Program to insert the node at the beginning of
# Linked List
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
def insert_at_front(head, new_data):
# Create a new node with the given data
new_node = Node(new_data)
# Make the next of the new node point to the current head
new_node.next = head
# Return the new node as the new head of the list
return new_node
def print_list(head):
curr = head
while curr is not None:
print(f" {curr.data}", end="")
curr = curr.next
print()
if __name__ == "__main__":
# Create the linked list 2->3->4->5
head = Node(2)
head.next = Node(3)
head.next.next = Node(4)
head.next.next.next = Node(5)
# Print the original list
print("Original Linked List:", end="")
print_list(head)
# Insert a new node at the front of the list
print("After inserting Nodes at the front:", end="")
data = 1
head = insert_at_front(head, data)
# Print the updated list
print_list(head)
C#
// C# Program to insert the node at the beginning of
// Linked List
using System;
public class Node
{
public int data;
public Node next;
public Node(int newData)
{
data = newData;
next = null;
}
}
public class GFG
{
// Function to insert a new node at the beginning of the list
public static Node InsertAtFront(Node head, int newData)
{
// Create a new node with the given data
Node newNode = new Node(newData);
// Make the next of the new node point to the current head
newNode.next = head;
// Return the new node as the new head of the list
return newNode;
}
public static void PrintList(Node head)
{
Node curr = head;
while (curr != null){
Console.Write(" " + curr.data);
curr = curr.next;
}
Console.WriteLine();
}
public static void Main()
{
// Create the linked list 2->3->4->5
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
// Print the original list
Console.WriteLine("Original Linked List:");
PrintList(head);
// Insert a new node at the front of the list
Console.WriteLine("After inserting Nodes at the front:");
int data = 1;
head = InsertAtFront(head, data);
// Print the updated list
PrintList(head);
}
}
JavaScript
// JavaScript Program to insert the node at the beginning of
// Linked List
class Node {
constructor(newData)
{
this.data = newData;
this.next = null;
}
}
// Function to insert a new node at the beginning of the
// list
function insertAtFront(head, newData)
{
// Create a new node with the given data
const newNode = new Node(newData);
// Make the next of the new node point to the current
// head
newNode.next = head;
// Return the new node as the new head of the list
return newNode;
}
function printList(head)
{
let curr = head;
let result = "";
while (curr !== null) {
result += " " + curr.data;
curr = curr.next;
}
console.log(result);
}
// Create the linked list 2->3->4->5
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
// Print the original list
console.log("Original Linked List:");
printList(head);
// Insert a new node at the front of the list
console.log("After inserting Nodes at the front:");
const data = 1;
head = insertAtFront(head, data);
// Print the updated list
printList(head);
OutputOriginal Linked List: 2 3 4 5
After inserting Nodes at the front: 1 2 3 4 5
Time Complexity: O(1), We have a pointer to the head and we can directly attach a node and update the head pointer. So, the Time complexity of inserting a node at the head position is O(1).
Auxiliary Space: O(1)
If we want to insert a new node after a specific node, we first locate that node. Once we find it, we set the new node’s next reference to point to the node that follows the given node. Then, we update the given node’s next to point to the new node. This requires traversing the list to find the specified node.

Insertion after a given node in Linked List
Approach:
- Initialize a pointer curr to traverse the list starting from head.
- Loop through the list to find the node with data equal to key.
- If not found then return from function.
- Create a new node, say new_node initialized with the given data.
- Make the next pointer of new_node as next of given node.
- Update the next pointer of given node point to the new_node.
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node after a Given Node in Linked
// List
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value)
{
data = value;
next = nullptr;
}
};
// Function to insert a new node after a given node
Node* insertAfter(Node* head, int key, int newData)
{
// Initilize curr Pointer to head
Node* curr = head;
// Iterate over Linked List to find the key
while (curr != nullptr) {
if (curr->data == key)
break;
curr = curr->next;
}
// if curr becomes NULL means, given key is not
// found in linked list
if (curr == nullptr)
return head;
// Allocate new node by given data and point
// the next of newNode to curr's next &
// point current next to newNode
Node* newNode = new Node(newData);
newNode->next = curr->next;
curr->next = newNode;
return head;
}
void printList(Node* node)
{
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
int main()
{
// Create the linked list 2->3->4->5
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(5);
head->next->next->next = new Node(6);
cout << "Original Linked List: ";
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = insertAfter(head, key, newData);
cout << "Linked List after insertion: ";
printList(head);
return 0;
}
C
// C Program to Insert a Node after a Given Node in Linked
// List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data);
// Function to insert a new node after a given node
struct Node* insertAfter(struct Node* head, int key,
int newData)
{
struct Node* curr = head;
// Iterate over Linked List to find the key
while (curr != NULL) {
if (curr->data == key)
break;
curr = curr->next;
}
// If curr becomes NULL means, given key is not found
if (curr == NULL)
return head;
// Allocate new node by given data and point
// the next of newNode to curr's next &
// point current next to newNode
struct Node* newNode = createNode(newData);
newNode->next = curr->next;
curr->next = newNode;
return head;
}
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
struct Node* createNode(int data)
{
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main()
{
// Create the linked list 2->3->5->6
struct Node* head = createNode(2);
head->next = createNode(3);
head->next->next = createNode(5);
head->next->next->next = createNode(6);
printf("Original Linked List: ");
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = insertAfter(head, key, newData);
printf("Linked List after insertion: ");
printList(head);
return 0;
}
Java
// Java Program to Insert a Node after a Given Node in
// Linked List
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
public class GFG {
// Function to insert a new node after a given node
public static Node insertAfter(Node head, int key,
int newData)
{
Node curr = head;
// Iterate over Linked List to find the key
while (curr != null) {
if (curr.data == key)
break;
curr = curr.next;
}
// if curr becomes null means, given key is not
// found in linked list
if (curr == null)
return head;
// Allocate new node by given data and point
// the next of newNode to curr's next &
// point current next to newNode
Node newNode = new Node(newData);
newNode.next = curr.next;
curr.next = newNode;
return head;
}
public static void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args)
{
// Create the linked list 2->3->5->6
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);
System.out.println("Original Linked List: ");
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node
// having data 3
head = insertAfter(head, key, newData);
System.out.println("Linked List after insertion: ");
printList(head);
}
}
Python
# Python Program to Insert a Node after a Given Node in Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a new node after a given node
def insertAfter(head, key, newData):
curr = head
# Iterate over Linked List to find the key
while curr is not None:
if curr.data == key:
break
curr = curr.next
# if curr becomes None means, given key is not found in linked list
if curr is None:
return head
# Allocate new node by given data and point
# the next of newNode to curr's next &
# point current next to newNode
newNode = Node(newData)
newNode.next = curr.next
curr.next = newNode
return head
def printList(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()
if __name__ == "__main__":
# Create the linked list 2->3->5->6
head = Node(2)
head.next = Node(3)
head.next.next = Node(5)
head.next.next.next = Node(6)
print("Original Linked List: ", end="")
printList(head)
# Key: Insert node after key
key = 3
newData = 4
# Insert a new node with data 4 after the node having data 3
head = insertAfter(head, key, newData)
print("Linked List after insertion: ", end="")
printList(head)
C#
// C# Program to Insert a Node after a Given Node in Linked
// List
using System;
public class Node {
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public class LinkedList {
// Function to insert a new node after a given node
public static Node InsertAfter(Node head, int key,
int newData)
{
// Initialize curr pointer to head
Node curr = head;
// Iterate over linked list to find the key
while (curr != null) {
if (curr.data == key)
break;
curr = curr.next;
}
// If curr becomes null, it means the given key is
// not found in the linked list
if (curr == null)
return head;
// Allocate new node by given data and point
// the next of newNode to curr's next &
// point current next to newNode
Node newNode = new Node(newData);
newNode.next = curr.next;
curr.next = newNode;
return head;
}
public static void PrintList(Node node)
{
while (node != null) {
Console.Write(node.data + " ");
node = node.next;
}
Console.WriteLine();
}
public static void Main()
{
// Create the linked list 2->3->5->6
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);
Console.WriteLine("Original Linked List: ");
PrintList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node
// having data 3
head = InsertAfter(head, key, newData);
Console.WriteLine("Linked List after insertion: ");
PrintList(head);
}
}
JavaScript
// JavaScript Program to Insert a Node after a Given
// Node in Linked List
class Node {
constructor(data)
{
this.data = data;
this.next = null;
}
}
// Function to insert a new node after a given node
function insertAfter(head, key, newData)
{
let curr = head;
// Iterate over Linked List to find the key
while (curr !== null) {
if (curr.data === key)
break;
curr = curr.next;
}
// if curr becomes null means, given key is not found in
// linked list
if (curr === null)
return head;
// Allocate new node by given data and point
// the next of newNode to curr's next &
// point current next to newNode
let newNode = new Node(newData);
newNode.next = curr.next;
curr.next = newNode;
return head;
}
function printList(node)
{
while (node !== null) {
process.stdout.write(node.data + " ");
node = node.next;
}
console.log();
}
// Create the linked list 2->3->5->6
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);
console.log("Original Linked List: ");
printList(head);
// Key: Insert node after key
let key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = insertAfter(head, key, newData);
console.log("Linked List after insertion: ");
printList(head);
OutputOriginal Linked List: 2 3 5 6
Linked List after insertion: 2 3 4 5 6
Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
To insert a new node at a specific position, we need to traverse the list to position – 1. If the position is valid, we adjust the pointers similarly such that the next pointer of the new node points to the next of current nod and next pointer of current node points to the new node.

Insertion at specific position in Linked List
Algorithm:
- Traverse the Linked list upto position-1 nodes.
- Once all the position-1 nodes are traversed, allocate memory and the given data to the new node.
- Point the next pointer of the new node to the next of current node.
- Point the next pointer of current node to the new node.
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node At a Specific Position in
// Linked List
#include <iostream>
using namespace std;
// Definition for singly-linked list node.
struct Node {
int data;
Node* next;
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
// Function to insert a node at a specific position in the
// linked list.
Node* insertAtPosition(Node* head, int position, int data)
{
Node* newNode = new Node(data);
// If inserting at the beginning
if (position == 1) {
newNode->next = head;
head = newNode;
return head;
}
Node* current = head;
// Traverse the list to find the node before the
// insertion point
for (int i = 1; i < position - 1 && current != nullptr;
++i) {
current = current->next;
}
// If the position is out of bounds
if (current == nullptr) {
cout << "Position is out of bounds." << endl;
delete newNode; // Deallocate memory to prevent
// memory leak
return head;
}
// Insert the new node at the specified position
newNode->next = current->next;
current->next = newNode;
return head;
}
// Function to print the linked list.
void printList(Node* head)
{
while (head != nullptr) {
cout << " " << head->data;
head = head->next;
}
cout << endl;
}
int main()
{
// Creating the list 3->5->8->10
Node* head = new Node(3);
head->next = new Node(5);
head->next->next = new Node(8);
head->next->next->next = new Node(10);
cout << "Linked list before insertion:";
printList(head);
// Insert a new node with data 12 at position 3
int data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
cout << "Linked list after insertion of 12 at position "
"3:";
printList(head);
return 0;
}
C
// C Program to Insert a Node At a Specific Position in
// Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data);
// Function to insert a node at a specific position in the
// linked list
struct Node* insertAtPosition(struct Node* head,
int position, int data)
{
struct Node* newNode = createNode(data);
// If inserting at the beginning
if (position == 1) {
newNode->next = head;
head = newNode;
return head;
}
struct Node* current = head;
for (int i = 1; i < position - 1 && current != NULL;
++i) {
current = current->next;
}
// If the position is out of bounds
if (current == NULL) {
printf("Position is out of bounds.\n");
free(newNode);
return head;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
void printList(struct Node* head)
{
while (head != NULL) {
printf(" %d", head->data);
head = head->next;
}
printf("\n");
}
struct Node* createNode(int data)
{
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main()
{
// Creating the list 3->5->8->10
struct Node* head = createNode(3);
head->next = createNode(5);
head->next->next = createNode(8);
head->next->next->next = createNode(10);
printf("Linked list before insertion:");
printList(head);
// Insert a new node with data 12 at position 3
int data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
printf("Linked list after insertion of 12 at position %d:", pos);
printList(head);
return 0;
}
Java
// Java Program to Insert a Node At a Specific Position in
// Linked List
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
public class GFG {
// Function to insert a node at a specific position in
// the linked list
public static Node
insertAtPosition(Node head, int position, int data)
{
Node newNode = new Node(data);
// If inserting at the beginning
if (position == 1) {
newNode.next = head;
head = newNode;
return head;
}
Node current = head;
for (int i = 1; i < position - 1 && current != null;
++i) {
current = current.next;
}
// If the position is out of bounds
if (current == null) {
System.out.println(
"Position is out of bounds.");
return head;
}
newNode.next = current.next;
current.next = newNode;
return head;
}
public static void printList(Node head)
{
while (head != null) {
System.out.print(" " + head.data);
head = head.next;
}
System.out.println();
}
public static void main(String[] args)
{
// Creating the list 3->5->8->10
Node head = new Node(3);
head.next = new Node(5);
head.next.next = new Node(8);
head.next.next.next = new Node(10);
System.out.print("Linked list before insertion:");
printList(head);
// Insert a new node with data 12 at position 3
int data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
System.out.print("Linked list after insertion of 12 at position " + pos + ":");
printList(head);
}
}
Python
# Python Program to Insert a Node At a Specific Position in Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def insert_at_position(head, position, data):
new_node = Node(data)
# If inserting at the beginning
if position == 1:
new_node.next = head
head = new_node
return head
current = head
for _ in range(1, position - 1):
if current is None:
break
current = current.next
# If the position is out of bounds
if current is None:
print("Position is out of bounds.")
return head
new_node.next = current.next
current.next = new_node
return head
def print_list(head):
while head:
print(f" {head.data}", end="")
head = head.next
print()
# Creating the list 3->5->8->10
head = Node(3)
head.next = Node(5)
head.next.next = Node(8)
head.next.next.next = Node(10)
print("Linked list before insertion:", end="")
print_list(head)
# Insert a new node with data 12 at position 3
data, pos = 12, 2
head = insert_at_position(head, pos, data)
print(f"Linked list after insertion of 12 at position {pos}:", end="")
print_list(head)
C#
// C# Program to Insert a Node At a Specific Position in
// Linked List
using System;
class Node {
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
class LinkedList {
public Node InsertAtPosition(Node head, int position,
int data)
{
Node newNode = new Node(data);
// If inserting at the beginning
if (position == 1) {
newNode.next = head;
head = newNode;
return head;
}
Node current = head;
// Traverse the list to find the node before the
// insertion point
for (int i = 1; i < position - 1 && current != null;
++i) {
current = current.next;
}
// If the position is out of bounds
if (current == null) {
Console.WriteLine("Position is out of bounds.");
return head;
}
// Insert the new node at the specified position
newNode.next = current.next;
current.next = newNode;
return head;
}
public void PrintList(Node head)
{
while (head != null) {
Console.Write(" " + head.data);
head = head.next;
}
Console.WriteLine();
}
}
class Program {
static void Main()
{
// Creating the list 3->5->8->10
Node head = new Node(3);
head.next = new Node(5);
head.next.next = new Node(8);
head.next.next.next = new Node(10);
LinkedList linkedList = new LinkedList();
Console.Write("Linked list before insertion:");
linkedList.PrintList(head);
// Insert a new node with data 12 at position 2
int data = 12, pos = 2;
head = linkedList.InsertAtPosition(head, pos, data);
Console.Write(
"Linked list after insertion of 12 at position "
+ pos + ":");
linkedList.PrintList(head);
}
}
JavaScript
// Javascript Program to Insert a Node At a Specific
// Position in Linked List
class Node {
constructor(data)
{
this.data = data;
this.next = null;
}
}
// Function to insert a node at a specific position in the
// linked list
function insertAtPosition(head, position, data)
{
let newNode = new Node(data);
// If inserting at the beginning
if (position === 1) {
newNode.next = head;
head = newNode;
return head;
}
let current = head;
for (let i = 1; i < position - 1 && current !== null;
++i) {
current = current.next;
}
// If the position is out of bounds
if (current === null) {
console.log("Position is out of bounds.");
return head;
}
newNode.next = current.next;
current.next = newNode;
return head;
}
function printList(head)
{
let current = head;
while (current !== null) {
process.stdout.write(` ${current.data}`);
current = current.next;
}
console.log();
}
// Creating the list 3->5->8->10
let head = new Node(3);
head.next = new Node(5);
head.next.next = new Node(8);
head.next.next.next = new Node(10);
console.log("Linked list before insertion:");
printList(head);
// Insert a new node with data 12 at position 3
let data = 12, pos = 2;
head = insertAtPosition(head, pos, data);
console.log(`Linked list after insertion of 12 at position ${pos}:`);
printList(head);
OutputLinked list before insertion: 3 5 8 10
Linked list after insertion of 12 at position 3: 3 12 5 8 10
Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
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.

Insertion at end of Linked List
Algorithm:
- Go to the last node of the Linked List
- Change the next pointer of last node from NULL to the new node
- Make the next pointer of new node as NULL to show the end of Linked List
Below is the implementation of the approach:
C++
// C++ Program to Insert a Node at the End of Linked List
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int new_data)
{
data = new_data;
next = nullptr;
}
};
// Function appends a new node at the end and returns the
// head.
Node* insertAtEnd(Node* head, int new_data)
{
// Create a new node
Node* new_node = new Node(new_data);
// If the Linked List is empty, make
// the new node as the head and return
if (head == nullptr) {
return new_node;
}
// Store the head reference in a temporary variable
Node* last = head;
// Traverse till the last node
while (last->next != nullptr) {
last = last->next;
}
// Change the next pointer of the last node
// to point to the new node
last->next = new_node;
// Return the head of the list
return head;
}
void printList(Node* node)
{
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
}
int main()
{
// Create a linked list: 2->3->4->5->6
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(5);
head->next->next->next->next = new Node(6);
cout << "Created Linked list is: ";
printList(head);
// Example of appending a node at the end
head = insertAtEnd(head, 1);
cout << "\nAfter inserting 1 at the end: ";
printList(head);
return 0;
}
C
// C Program to Insert a Node at the End of Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int new_data);
// Function appends a new node at the end and returns the
// head.
struct Node* insertAtEnd(struct Node* head, int new_data)
{
// Create a new node
struct Node* new_node = createNode(new_data);
// If the Linked List is empty, make
// the new node as the head and return
if (head == NULL) {
return new_node;
}
// Store the head reference in a temporary variable
struct Node* last = head;
// Traverse till the last node
while (last->next != NULL) {
last = last->next;
}
// Change the next pointer of the last node
// to point to the new node
last->next = new_node;
// Return the head of the list
return head;
}
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d", node->data);
node = node->next;
}
}
struct Node* createNode(int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
int main()
{
// Create a linked list:
// 2 -> 3 -> 4 -> 5 -> 6
struct Node* head = createNode(2);
head->next = createNode(3);
head->next->next = createNode(4);
head->next->next->next = createNode(5);
head->next->next->next->next = createNode(6);
printf("Created Linked list is:");
printList(head);
// Example of appending a node at the end
head = insertAtEnd(head, 1);
printf("\nAfter inserting 1 at the end:");
printList(head);
return 0;
}
Java
// Java Program to Insert a Node at the End of Linked List
class Node {
int data;
Node next;
Node(int newData)
{
data = newData;
next = null;
}
}
public class GfG {
// Function appends a new node at the end and returns
// the head.
static Node insertAtEnd(Node head, int newData)
{
// Create a new node
Node newNode = new Node(newData);
// If the Linked List is empty, make the new
// node as the head and return
if (head == null) {
return newNode;
}
// Store the head reference in a temporary variable
Node last = head;
// Traverse till the last node
while (last.next != null) {
last = last.next;
}
// Change the next pointer of the
// last node to point to the new node
last.next = newNode;
// Return the head of the list
return head;
}
public static void printList(Node node)
{
while (node != null) {
System.out.print(" " + node.data);
node = node.next;
}
}
public static void main(String[] args)
{
// Create a linked list:
// 2 -> 3 -> 4 -> 5 -> 6
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(6);
System.out.print("Created Linked list is:");
printList(head);
// Example of appending a node at the end
head = insertAtEnd(head, 1);
System.out.print("\nAfter inserting 1 at the end:");
printList(head);
}
}
Python
# Python Program to Insert a Node at the End of Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function appends a new node at the end and returns the head.
def insertAtEnd(head, new_data):
# Create a new node
new_node = Node(new_data)
# If the Linked List is empty, make the
# new node as the head and return
if head is None:
return new_node
# Store the head reference in a temporary variable
last = head
# Traverse till the last node
while last.next:
last = last.next
# Change the next pointer of the last
# node to point to the new node
last.next = new_node
# Return the head of the list
return head
def print_list(node):
while node:
print(node.data, end=" ")
node = node.next
if __name__ == "__main__":
# Create a linked list:
# 2 -> 3 -> 4 -> 5 -> 6
head = Node(2)
head.next = Node(3)
head.next.next = Node(4)
head.next.next.next = Node(5)
head.next.next.next.next = Node(6)
print("Created Linked list is:", end="")
print_list(head)
# Example of appending a node at the end
head = insertAtEnd(head, 1)
print("\nAfter inserting 1 at the end:", end="")
print_list(head)
C#
// C# Program to Insert a Node at the End of Linked List
using System;
public class Node {
public int data;
public Node next;
public Node(int newData)
{
data = newData;
next = null;
}
}
public class GFG {
// Function appends a new node at the end and returns the head.
public static Node InsertAtEnd(Node head, int newData)
{
// Create a new node
Node newNode = new Node(newData);
// If the Linked List is empty, make the new node as
// the head and return
if (head == null) {
return newNode;
}
// Store the head reference in a temporary variable
Node last = head;
// Traverse till the last node
while (last.next != null) {
last = last.next;
}
// Change the next pointer of the last node to point
// to the new node
last.next = newNode;
// Return the head of the list
return head;
}
public static void PrintList(Node node)
{
while (node != null) {
Console.Write(node.data + " ");
node = node.next;
}
}
public static void Main()
{
// Create a linked list: 2->3->4->5->6
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(6);
Console.WriteLine("Created Linked list is: ");
PrintList(head);
// Example of appending a node at the end
head = InsertAtEnd(head, 1);
Console.WriteLine(
"\nAfter inserting 1 at the end: ");
PrintList(head);
}
}
JavaScript
// Javascript Program to Insert a Node at the End of Linked List
class Node {
constructor(data)
{
this.data = data;
this.next = null;
}
}
// Function Appends a new node at the end
// and returns the head.
function insertAtEnd(head, newData)
{
// Create a new node
const newNode = new Node(newData);
// If the Linked List is empty,
// make the new node as the head
if (head === null) {
return newNode;
}
// Store the head reference in a
// temporary variable
let last = head;
// Traverse till the last node
while (last.next !== null) {
last = last.next;
}
// Change the next pointer of the
// last node to point to the new node
last.next = newNode;
// Return the head of the list
return head;
}
function printList(node)
{
while (node !== null) {
console.log(node.data + " ");
node = node.next;
}
}
// Create a linked list:
// 2 -> 3 -> 4 -> 5 -> 6
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(6);
console.log("Created Linked list is:");
printList(head);
// Example of appending a node
// at the end
head = insertAtEnd(head, 1);
console.log("\nAfter inserting 1 at the end:");
printList(head);
OutputCreated Linked list is: 2 3 4 5 6
After inserting 1 at the end: 2 3 4 5 6 1
Time complexity: O(N), where N is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work.
Auxiliary Space: O(1)
Please Login to comment...