Insert a linked list into another linked list
Last Updated :
04 Sep, 2024
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place.
Examples:
Input: a = 3, b = 4
head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103
Output: 10 -> 11 -> 12 -> 100 -> 101 -> 102 -> 103 -> 15
Explanation: Remove the nodes from 3rd index till 4th index from head1 and insert head2 at their place.
Input: a = 0, b = 1
head1: 1 -> 2 , head2: 3 -> 4
Output: 3 -> 4
Explanation: Remove the nodes from 0th index till 1th index from head1 and insert head2 at their place.
Approach :
The idea is to start traversing from head1 and identify the node at position a - 1 and b. Let prev points to (a-1)th node and curr points to bth node in head1. Now update the pointer as following:
- Update prev's next to point to head2 node as we need to remove some nodes in head1 after prev.
- Start traversing head2 until we reach to end, and update the next pointer of the end node of head2 to curr's next. This will remove the node from a to b in head1.
C++
// C++ code to insert a linked list into
// another linked list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to merge head2 into head1 by removing nodes
// from the ath to the bth position and inserting head2
Node *mergeInBetween(Node *head1, int a, int b, Node *head2) {
Node *curr = head1;
Node *prev = nullptr;
// Traverse to the node just before position
// 'a' and the node at position 'b'
for (int i = 0; curr != nullptr; ++i) {
if (i == a - 1) {
// Node just before position 'a'
prev = curr;
}
if (i == b) {
// Update the next pointer of the
// node at position 'a - 1'
prev->next = head2;
// Traverse to the end of head2
Node *endHead2 = head2;
while (endHead2->next != nullptr) {
endHead2 = endHead2->next;
}
// Connect the end of head2 to the
// node after position 'b'
endHead2->next = curr->next;
break;
}
curr = curr->next;
}
return head1;
}
void printList(Node *head) {
Node *curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Creating head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15
Node *head1 = new Node(10);
head1->next = new Node(11);
head1->next->next = new Node(12);
head1->next->next->next = new Node(13);
head1->next->next->next->next = new Node(14);
head1->next->next->next->next->next = new Node(15);
// Creating head2: 100 -> 101 -> 102 -> 103
Node *head2 = new Node(100);
head2->next = new Node(101);
head2->next->next = new Node(102);
head2->next->next->next = new Node(103);
head1 = mergeInBetween(head1, 3, 4, head2);
printList(head1);
return 0;
}
C
// C code to insert a linked list into
// another linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
// Function to merge head2 into head1 by removing nodes
// from the ath to the bth position and inserting head2
struct Node* mergeInBetween(struct Node* head1, int a, int b,
struct Node* head2) {
struct Node* curr = head1;
struct Node* prev = NULL;
// Traverse to the node just before position 'a' and
// the node at position 'b'
for (int i = 0; curr != NULL; ++i) {
if (i == a - 1) {
// Node just before position 'a'
prev = curr;
}
if (i == b) {
// Update the next pointer of the node
// at position 'a - 1'
prev->next = head2;
// Traverse to the end of head2
struct Node* endHead2 = head2;
while (endHead2->next != NULL) {
endHead2 = endHead2->next;
}
// Connect the end of head2 to the
// node after position 'b'
endHead2->next = curr->next;
break;
}
curr = curr->next;
}
return head1;
}
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node* createNode(int x) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
int main() {
// Creating head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15
struct Node* head1 = createNode(10);
head1->next = createNode(11);
head1->next->next = createNode(12);
head1->next->next->next = createNode(13);
head1->next->next->next->next = createNode(14);
head1->next->next->next->next->next = createNode(15);
// Creating head2: 100 -> 101 -> 102 -> 103
struct Node* head2 = createNode(100);
head2->next = createNode(101);
head2->next->next = createNode(102);
head2->next->next->next = createNode(103);
head1 = mergeInBetween(head1, 3, 4, head2);
printList(head1);
return 0;
}
Java
// Java code to insert a linked list
// into another linked list
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to merge head2 into head1 by removing nodes
// from the ath to the bth position and inserting head2
static Node mergeInBetween(Node head1, int a, int b, Node head2) {
Node curr = head1;
Node prev = null;
// Traverse to the node just before position
// 'a' and the node at position 'b'
for (int i = 0; curr != null; ++i) {
if (i == a - 1) {
prev = curr;
}
if (i == b) {
// Update the next pointer of the node at
// position 'a - 1'
prev.next = head2;
// Traverse to the end of head2
Node endHead2 = head2;
while (endHead2.next != null) {
endHead2 = endHead2.next;
}
// Connect the end of head2 to the node
// after position 'b'
endHead2.next = curr.next;
break;
}
curr = curr.next;
}
return head1;
}
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) {
// Creating head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15
Node head1 = new Node(10);
head1.next = new Node(11);
head1.next.next = new Node(12);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(14);
head1.next.next.next.next.next = new Node(15);
// Creating head2: 100 -> 101 -> 102 -> 103
Node head2 = new Node(100);
head2.next = new Node(101);
head2.next.next = new Node(102);
head2.next.next.next = new Node(103);
head1 = mergeInBetween(head1, 3, 4, head2);
printList(head1);
}
}
Python
# Python code to insert a linked list
# into another linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
def merge_in_between(head1, a, b, head2):
curr = head1
prev = None
# Traverse to the node just before
# position 'a' and the node at position 'b'
for i in range(b + 1):
if i == a - 1:
prev = curr
if i == b:
# Update the next pointer of
# the node at position 'a - 1'
prev.next = head2
# Traverse to the end of head2
end_head2 = head2
while end_head2.next:
end_head2 = end_head2.next
# Connect the end of head2
# to the node after position 'b'
end_head2.next = curr.next
break
curr = curr.next
return head1
def print_list(head):
curr = head
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Creating head1:
# 10 -> 11 -> 12 -> 13 -> 14 -> 15
head1 = Node(10)
head1.next = Node(11)
head1.next.next = Node(12)
head1.next.next.next = Node(13)
head1.next.next.next.next = Node(14)
head1.next.next.next.next.next = Node(15)
# Creating head2: 100 -> 101 -> 102 -> 103
head2 = Node(100)
head2.next = Node(101)
head2.next.next = Node(102)
head2.next.next.next = Node(103)
head1 = merge_in_between(head1, 3, 4, head2)
print_list(head1)
C#
// C# code to insert a linked list
// into another linked list
using System;
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class GfG {
// Function to merge head2 into head1 by removing nodes
// from the ath to the bth position and inserting head2
static Node MergeInBetween(Node head1, int a,
int b, Node head2) {
Node curr = head1;
Node prev = null;
// Traverse to the node just before position 'a' and
// the node at position 'b'
for (int i = 0; curr != null; ++i) {
if (i == a - 1) {
prev = curr;
}
if (i == b) {
// Update the next pointer of the node at
// position 'a - 1'
prev.next = head2;
// Traverse to the end of head2
Node endHead2 = head2;
while (endHead2.next != null) {
endHead2 = endHead2.next;
}
// Connect the end of head2 to the node
// after position 'b'
endHead2.next = curr.next;
break;
}
curr = curr.next;
}
return head1;
}
static void PrintList(Node head) {
Node curr = head;
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
Console.WriteLine();
}
static void Main() {
// Creating head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15
Node head1 = new Node(10);
head1.next = new Node(11);
head1.next.next = new Node(12);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(14);
head1.next.next.next.next.next = new Node(15);
// Creating head2: 100 -> 101 -> 102 -> 103
Node head2 = new Node(100);
head2.next = new Node(101);
head2.next.next = new Node(102);
head2.next.next.next = new Node(103);
head1 = MergeInBetween(head1, 3, 4, head2);
PrintList(head1);
}
}
JavaScript
// JavaScript code to insert a linked list into another
// linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to merge head2 into head1 by removing nodes
// from the ath to the bth position and inserting head2
function mergeInBetween(head1, a, b, head2) {
let curr = head1;
let prev = null;
// Traverse to the node just before position 'a' and the
// node at position 'b'
for (let i = 0; curr !== null; ++i) {
if (i === a - 1) {
prev = curr;
}
if (i === b) {
// Update the next pointer of the node at
// position 'a - 1'
prev.next = head2;
// Traverse to the end of head2
let endHead2 = head2;
while (endHead2.next !== null) {
endHead2 = endHead2.next;
}
// Connect the end of head2 to the node after
// position 'b'
endHead2.next = curr.next;
break;
}
curr = curr.next;
}
return head1;
}
function printList(head) {
let curr = head;
while (curr !== null) {
console.log(curr.data + " ");
curr = curr.next;
}
console.log();
}
// Creating head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15
let head1 = new Node(10);
head1.next = new Node(11);
head1.next.next = new Node(12);
head1.next.next.next = new Node(13);
head1.next.next.next.next = new Node(14);
head1.next.next.next.next.next = new Node(15);
// Creating head2: 100 -> 101 -> 102 -> 103
let head2 = new Node(100);
head2.next = new Node(101);
head2.next.next = new Node(102);
head2.next.next.next = new Node(103);
head1 = mergeInBetween(head1, 3, 4, head2);
printList(head1);
Output10 11 12 100 101 102 103 15
Time Complexity: O(m + n), m is the length of head1 and n is the length of head2.
Auxiliary Space: O(1)
Similar Reads
Merge a linked list into another linked list at alternate positions Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer.Example:Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4-
8 min read
Insertion Sort for Doubly Linked List Given a doubly linked list, the task is to sort the doubly linked list in non-decreasing order using the insertion sort.Examples:Input: head: 5<->3<->4<->1<->2Output: 1<->2<->3<->4<->5Explanation: Doubly Linked List after sorting using insertion sort t
10 min read
Insertion Sort for Singly Linked List Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm.Examples:Input: 5->4->1->3->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4The prerequisite is Insertion Sort on Array. The idea is to
8 min read
Insertion in Linked List Insertion in a linked list involves adding a new node at a specified position in the list. There are several types of insertion based on the position where the new node is to be added:At the front of the linked list Before a given node.After a given node.At a specific position.At the end of the link
4 min read
Insert a whole linked list into other at k-th position Given two linked lists and a number k. Insert second linked list in to first at k-th position Examples: Input : a : 1->2->3->4->5->NULL b : 7->8->9->10->11->NULL k = 2 Output :1->2->7->8->9->10->11->3->4->5->NULL Input : a: 10->15->20
10 min read
Linked List of Linked List Linked list of linkeÂd list, also known as nested linkeÂd lists, is a type of Linked List where each main node stores another full linked list. This structure beats old, plain linked lists. It gives way more flexibility to store and manage compleÂx data. In this article we will learn about the bas
9 min read
Insertion in a Doubly Linked List Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list.Table of ContentInsertion a
6 min read
Insertion in Circular Singly Linked List In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the list. In a circular linked list, the last node connects back to the first node, creating a loop.There are four main ways to add
12 min read
Insert Node at the End of a Linked List Given a linked list, the task is to insert a new node at the end of the linked list.Examples:Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1Approach:Â Inserting at the end invol
9 min read
Insertion in Unrolled Linked List An unrolled linked list is a linked list of small arrays, all of the same size where each is so small that the insertion or deletion is fast and quick, but large enough to fill the cache line. An iterator pointing into the list consists of both a pointer to a node and an index into that node contain
11 min read