Insert node into the middle of the linked list
Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.
Examples:
Input : list: 1->2->4->5, x = 3
Output : 1->2->3->4->5
Input : list: 5->10->4->32->16, x = 41
Output : 5->10->4->41->32->16
Insert node into the middle of the linked list using the length of the Linked List:
The idea is to first find the length of linked list and then insert the x node after the half length of the linked list.
Follow the steps below to solve the problem:
- Iterate over the linked list to calculate the length
- Now insert the node x in the middle of the linked list i.e (n + 1) / 2
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* getNode( int data)
{
Node* newNode = (Node*) malloc ( sizeof (Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertAtMid(Node** head_ref, int x)
{
if (*head_ref == NULL)
*head_ref = getNode(x);
else {
Node* newNode = getNode(x);
Node* ptr = *head_ref;
int len = 0;
while (ptr != NULL) {
len++;
ptr = ptr->next;
}
int count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = *head_ref;
while (count-- > 1)
ptr = ptr->next;
newNode->next = ptr->next;
ptr->next = newNode;
}
}
void display(Node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
}
int main()
{
Node* head = NULL;
head = getNode(1);
head->next = getNode(2);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
cout << "Linked list before insertion: " ;
display(head);
int x = 3;
insertAtMid(&head, x);
cout << "\nLinked list after insertion: " ;
display(head);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList
{
static Node head;
static class Node {
int data;
Node next;
Node( int d) {
data = d;
next = null ;
}
}
static void insertAtMid( int x)
{
if (head == null )
head = new Node(x);
else {
Node newNode = new Node(x);
Node ptr = head;
int len = 0 ;
while (ptr != null ) {
len++;
ptr = ptr.next;
}
int count = ((len % 2 ) == 0 ) ? (len / 2 ) :
(len + 1 ) / 2 ;
ptr = head;
while (count-- > 1 )
ptr = ptr.next;
newNode.next = ptr.next;
ptr.next = newNode;
}
}
static void display()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data + " " );
temp = temp.next;
}
}
public static void main (String[] args)
{
head = null ;
head = new Node( 1 );
head.next = new Node( 2 );
head.next.next = new Node( 4 );
head.next.next.next = new Node( 5 );
System.out.println( "Linked list before " +
"insertion: " );
display();
int x = 3 ;
insertAtMid(x);
System.out.println( "\nLinked list after" +
" insertion: " );
display();
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def insertAtMid(head, x):
if (head = = None ):
head = Node(x)
else :
newNode = Node(x)
ptr = head
length = 0
while (ptr ! = None ):
ptr = ptr. next
length + = 1
if (length % 2 = = 0 ):
count = length / 2
else :
(length + 1 ) / 2
ptr = head
while (count > 1 ):
count - = 1
ptr = ptr. next
newNode. next = ptr. next
ptr. next = newNode
def display(head):
temp = head
while (temp ! = None ):
print ( str (temp.data), end = " " )
temp = temp. next
head = Node( 1 )
head. next = Node( 2 )
head. next . next = Node( 4 )
head. next . next . next = Node( 5 )
print ( "Linked list before insertion: " , end = "")
display(head)
x = 3
insertAtMid(head, x)
print ( "\nLinked list after insertion: " , end = "")
display(head)
|
C#
using System;
public class LinkedList
{
static Node head;
public class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
static void insertAtMid( int x)
{
if (head == null )
head = new Node(x);
else
{
Node newNode = new Node(x);
Node ptr = head;
int len = 0;
while (ptr != null )
{
len++;
ptr = ptr.next;
}
int count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = head;
while (count-- > 1)
ptr = ptr.next;
newNode.next = ptr.next;
ptr.next = newNode;
}
}
static void display()
{
Node temp = head;
while (temp != null )
{
Console.Write(temp.data + " " );
temp = temp.next;
}
}
public static void Main ()
{
head = null ;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
Console.WriteLine( "Linked list before " +
"insertion: " );
display();
int x = 3;
insertAtMid(x);
Console.WriteLine( "\nLinked list after" +
" insertion: " );
display();
}
}
|
Javascript
<script>
var head;
class Node {
constructor(d) {
this .data = d;
this .next = null ;
}
}
function insertAtMid(x) {
if (head == null )
head = new Node(x);
else {
var newNode = new Node(x);
var ptr = head;
var len = 0;
while (ptr != null ) {
len++;
ptr = ptr.next;
}
var count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = head;
while (count-- > 1)
ptr = ptr.next;
newNode.next = ptr.next;
ptr.next = newNode;
}
}
function display() {
var temp = head;
while (temp != null ) {
document.write(temp.data + " " );
temp = temp.next;
}
}
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
document.write( "Linked list before "
+ "insertion: " );
display();
var x = 3;
insertAtMid(x);
document.write( "<br/>Linked list after" +
" insertion: " );
display();
</script>
|
Output
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(N), Using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Insert node into the middle of the linked list using Two Pointers:
Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast.
Follow the steps below to solve the problem:
- Initialize two-pointers fast and slow with head
- Move fast by two steps i.e fast = fast->next->next till it reaches end
- And slow = slow->next
- Now append node x after slow i.e. slow->next = x
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* getNode( int data)
{
Node* newNode = (Node*) malloc ( sizeof (Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertAtMid(Node** head_ref, int x)
{
if (*head_ref == NULL)
*head_ref = getNode(x);
else {
Node* newNode = getNode(x);
Node* slow = *head_ref;
Node* fast = (*head_ref)->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
newNode->next = slow->next;
slow->next = newNode;
}
}
void display(Node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
}
int main()
{
Node* head = NULL;
head = getNode(1);
head->next = getNode(2);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
cout << "Linked list before insertion: " ;
display(head);
int x = 3;
insertAtMid(&head, x);
cout << "\nLinked list after insertion: " ;
display(head);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList
{
static Node head;
static class Node {
int data;
Node next;
Node( int d) {
data = d;
next = null ;
}
}
static void insertAtMid( int x)
{
if (head == null )
head = new Node(x);
else {
Node newNode = new Node(x);
Node slow = head;
Node fast = head.next;
while (fast != null && fast.next
!= null )
{
slow = slow.next;
fast = fast.next.next;
}
newNode.next = slow.next;
slow.next = newNode;
}
}
static void display()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data + " " );
temp = temp.next;
}
}
public static void main (String[] args)
{
head = null ;
head = new Node( 1 );
head.next = new Node( 2 );
head.next.next = new Node( 4 );
head.next.next.next = new Node( 5 );
System.out.println( "Linked list before" +
" insertion: " );
display();
int x = 3 ;
insertAtMid(x);
System.out.println( "\nLinked list after" +
" insertion: " );
display();
}
}
|
Python3
class Node :
def __init__( self , d):
self .data = d
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def insertAtMid( self , x):
if ( self .head = = None ):
self .head = Node(x)
else :
newNode = Node(x)
slow = self .head
fast = self .head. next
while (fast ! = None and
fast. next ! = None ):
slow = slow. next
fast = fast. next . next
newNode. next = slow. next
slow. next = newNode
def display( self ):
temp = self .head
while (temp ! = None ):
print (temp.data, end = " " ),
temp = temp. next
ll = LinkedList()
ll.push( 5 )
ll.push( 4 )
ll.push( 2 )
ll.push( 1 )
print ( "Linked list before insertion: " ),
ll.display()
x = 3
ll.insertAtMid(x)
print ( "\nLinked list after insertion: " ),
ll.display()
|
C#
using System;
public class LinkedList
{
static Node head;
class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
static void insertAtMid( int x)
{
if (head == null )
head = new Node(x);
else
{
Node newNode = new Node(x);
Node slow = head;
Node fast = head.next;
while (fast != null && fast.next
!= null )
{
slow = slow.next;
fast = fast.next.next;
}
newNode.next = slow.next;
slow.next = newNode;
}
}
static void display()
{
Node temp = head;
while (temp != null )
{
Console.Write(temp.data + " " );
temp = temp.next;
}
}
public static void Main (String[] args)
{
head = null ;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
Console.WriteLine( "Linked list before" +
" insertion: " );
display();
int x = 3;
insertAtMid(x);
Console.WriteLine( "\nLinked list after" +
" insertion: " );
display();
}
}
|
Javascript
<script>
var head;
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function insertAtMid(x) {
if (head == null )
head = new Node(x);
else {
var newNode = new Node(x);
var slow = head;
var fast = head.next;
while (fast != null && fast.next != null )
{
slow = slow.next;
fast = fast.next.next;
}
newNode.next = slow.next;
slow.next = newNode;
}
}
function display() {
var temp = head;
while (temp != null ) {
document.write(temp.data + " " );
temp = temp.next;
}
}
head = null ;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
document.write(
"Linked list before" + " insertion: "
);
display();
var x = 3;
insertAtMid(x);
document.write(
"<br/>Linked list after" + " insertion: "
);
display();
</script>
|
Output
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(N), Using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...