Merge a linked list into another linked list at alternate positions Last Updated : 13 Sep, 2024 Comments Improve Suggest changes Like Article Like Report 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->2->5->3->6 , head2: 7->8 Input: head1: 10->12->21 , head2: 3->1->4Output: head1: 10->3->12->1->21->4, head2: <empty> Using Iterative Method – O(n) Time and O(1) Space:The idea is to start traversing from the beginning of both lists. For each step, take a node from the second list and insert it after a node from the first list. This process continues until we reach the end of one or both lists. If the second list is longer, remaining nodes will be kept as it is second list. C++ // C++ program to merge a linked list into another at // alternate positions #include <bits/stdc++.h> using namespace std; class Node{ public: int data; Node *next; Node(int x) { data = x; next = nullptr; } }; void printList(Node *head){ Node *curr = head; while (curr != NULL){ cout << curr->data << " "; curr = curr->next; } cout << endl; } // Function to merge two linked lists vector<Node *> merge(Node *head1, Node *head2) { // Initialize pointers to traverse the two lists Node *curr1 = head1; Node *curr2 = head2; // Traverse both lists and merge them while (curr1 != NULL && curr2 != NULL){ // Save the next nodes of the current // nodes in both lists Node *ptr1 = curr1->next; Node *ptr2 = curr2->next; // Insert the current node from the second list // after the current node from the first list curr2->next = curr1->next; curr1->next = curr2; // Update the pointers for the next iteration curr1 = ptr1; curr2 = ptr2; } return {head1, curr2}; } int main(){ // Creating first linked list 1->2->3 Node *head1 = new Node(1); head1->next = new Node(2); head1->next->next = new Node(3); // crating second listed list 4->5->6->7->8 Node *head2 = new Node(4); head2->next = new Node(5); head2->next->next = new Node(6); head2->next->next->next = new Node(7); head2->next->next->next->next = new Node(8); // Store first and second head points in array vector<Node *> ar = merge(head1, head2); printList(ar[0]); printList(ar[1]); return 0; } C // C program to merge a linked list into another at // alternate positions #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void printList(struct Node *head) { struct Node *curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); } // Function to merge two linked lists struct Node *merge(struct Node *head1, struct Node *head2) { struct Node *curr1 = head1; struct Node *curr2 = head2; struct Node *next1, *next2; // Traverse both lists and merge them while (curr1 != NULL && curr2 != NULL) { // Save the next nodes of the current // nodes in both lists next1 = curr1->next; next2 = curr2->next; // Insert the current node from the second list // after the current node from the first list curr2->next = curr1->next; curr1->next = curr2; // Update the pointers for the next iteration curr1 = next1; curr2 = next2; } // Return the remaining part of the second list return curr2; } 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 first linked list: 1->2->3 struct Node *head1 = createNode(1); head1->next = createNode(2); head1->next->next = createNode(3); // Creating the second linked list: 4->5->6->7->8 struct Node *head2 = createNode(4); head2->next = createNode(5); head2->next->next = createNode(6); head2->next->next->next = createNode(7); head2->next->next->next->next = createNode(8); struct Node *remaining = merge(head1, head2); // Print merged list and remaining list printList(head1); printList(remaining); return 0; } Java // Java program to merge a linked list into another at // alternate positions import java.util.*; class Node { int data; Node next; Node(int x) { data = x; next = null; } } class GfG { // Function to print a linked list static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.data + " "); curr = curr.next; } System.out.println(); } // Function to merge two linked lists static List<Node> merge(Node head1, Node head2) { // Initialize pointers to traverse the two lists Node temp1 = head1; Node temp2 = head2; // Traverse both lists and merge them while (temp1 != null && temp2 != null) { // Save the next nodes of the current nodes in // both lists Node ptr1 = temp1.next; Node ptr2 = temp2.next; // Insert the current node from the second list // after the current node from the first list temp2.next = temp1.next; temp1.next = temp2; // Update the pointers for the next iteration temp1 = ptr1; temp2 = ptr2; } return Arrays.asList(head1, temp2); } public static void main(String[] args) { // Creating first linked list 1->2->3 Node head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); // Creating second linked list 4->5->6->7->8 Node head2 = new Node(4); head2.next = new Node(5); head2.next.next = new Node(6); head2.next.next.next = new Node(7); head2.next.next.next.next = new Node(8); // Store first and second head points in array List<Node> ar = merge(head1, head2); printList(ar.get(0)); printList(ar.get(1)); } } Python # Python program to merge a linked list into another at # alternate positions class Node: def __init__(self, x): self.data = x self.next = None def printList(head): curr = head while curr: print(curr.data, end=" ") curr = curr.next print() # Function to merge two linked lists def merge(head1, head2): # Initialize pointers to traverse the two lists temp1 = head1 temp2 = head2 # Traverse both lists and merge them while temp1 is not None and temp2 is not None: # Save the next nodes of the current # nodes in both lists ptr1 = temp1.next ptr2 = temp2.next # Insert the current node from the second list # after the current node from the first list temp2.next = temp1.next temp1.next = temp2 # Update the pointers for the next iteration temp1 = ptr1 temp2 = ptr2 return [head1, temp2] if __name__ == "__main__": # Creating first linked list 1->2->3 head1 = Node(1) head1.next = Node(2) head1.next.next = Node(3) # Creating second linked list 4->5->6->7->8 head2 = Node(4) head2.next = Node(5) head2.next.next = Node(6) head2.next.next.next = Node(7) head2.next.next.next.next = Node(8) # Store first and second head points in array ar = merge(head1, head2) printList(ar[0]) printList(ar[1]) C# // C# program to merge a linked list into // another at alternate positions using System; using System.Collections.Generic; class Node { public int data; public Node next; public Node(int x) { data = x; next = null; } } class GfG { static void PrintList(Node head) { Node curr = head; while (curr != null) { Console.Write(curr.data + " "); curr = curr.next; } Console.WriteLine(); } // Function to merge two linked lists static List<Node> Merge(Node head1, Node head2) { // Initialize pointers to traverse the two lists Node temp1 = head1; Node temp2 = head2; // Traverse both lists and merge them while (temp1 != null && temp2 != null) { // Save the next nodes of the current nodes in // both lists Node ptr1 = temp1.next; Node ptr2 = temp2.next; // Insert the current node from the second list // after the current node from the first list temp2.next = temp1.next; temp1.next = temp2; // Update the pointers for the next iteration temp1 = ptr1; temp2 = ptr2; } return new List<Node>{ head1, temp2 }; } static void Main(string[] args) { // Creating first linked list 1->2->3 Node head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); // Creating second linked list 4->5->6->7->8 Node head2 = new Node(4); head2.next = new Node(5); head2.next.next = new Node(6); head2.next.next.next = new Node(7); head2.next.next.next.next = new Node(8); // Store first and second head points in array List<Node> ar = Merge(head1, head2); PrintList(ar[0]); PrintList(ar[1]); } } JavaScript // Javascript program to merge a linked list // into another at alternate positions class Node { constructor(x) { this.data = x; this.next = null; } } function printList(head) { let curr = head; while (curr !== null) { console.log(curr.data + " "); curr = curr.next; } console.log(); } // Function to merge two linked lists function merge(head1, head2) { // Initialize pointers to traverse the two lists let temp1 = head1; let temp2 = head2; // Traverse both lists and merge them while (temp1 !== null && temp2 !== null) { // Save the next nodes of the current nodes in both // lists let ptr1 = temp1.next; let ptr2 = temp2.next; // Insert the current node from the second list // after the current node from the first list temp2.next = temp1.next; temp1.next = temp2; // Update the pointers for the next iteration temp1 = ptr1; temp2 = ptr2; } return [ head1, temp2 ]; } // Creating first linked list 1->2->3 let head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); // Creating second linked list 4->5->6->7->8 let head2 = new Node(4); head2.next = new Node(5); head2.next.next = new Node(6); head2.next.next.next = new Node(7); head2.next.next.next.next = new Node(8); // Store first and second head points in array let ar = merge(head1, head2); printList(ar[0]); printList(ar[1]); Output1 4 2 5 3 6 7 8 Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists.Auxiliary Space: O(1). Comment More infoAdvertise with us Next Article Find a permutation that causes worst case of Merge Sort kartik Follow Improve Article Tags : Linked List DSA Amazon Practice Tags : AmazonLinked List Similar Reads Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Merge sort in different languagesC Program for Merge SortMerge Sort is a comparison-based sorting algorithm that works by dividing the input array into two halves, then calling itself for these two halves, and finally it merges the two sorted halves. In this article, we will learn how to implement merge sort in C language.What is Merge Sort Algorithm?Merg 3 min read C++ Program For Merge SortMerge Sort is a comparison-based sorting algorithm that uses divide and conquer paradigm to sort the given dataset. It divides the dataset into two halves, calls itself for these two halves, and then it merges the two sorted halves.In this article, we will learn how to implement merge sort in a C++ 4 min read Java Program for Merge SortMerge Sort is a divide-and-conquer algorithm. It divides the input array into two halves, calls itself the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are 3 min read Merge Sort in PythonMerge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorte 4 min read Merge Sort using Multi-threadingMerge Sort is a popular sorting technique which divides an array or list into two halves and then start merging them when sufficient depth is reached. Time complexity of merge sort is O(nlogn).Threads are lightweight processes and threads shares with other threads their code section, data section an 14 min read Variations of Merge Sort3-way Merge SortMerge Sort is a divide-and-conquer algorithm that recursively splits an array into two halves, sorts each half, and then merges them. A variation of this is 3-way Merge Sort, where instead of splitting the array into two parts, we divide it into three equal parts. In traditional Merge Sort, the arra 13 min read Iterative Merge SortGiven an array of size n, the task is to sort the given array using iterative merge sort.Examples:Input: arr[] = [4, 1, 3, 9, 7]Output: [1, 3, 4, 7, 9]Explanation: The output array is sorted.Input: arr[] = [1, 3 , 2]Output: [1, 2, 3]Explanation: The output array is sorted.You can refer to Merge Sort 9 min read In-Place Merge SortImplement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case. Examples: Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4 Input: arr[] = {56, 2, 45} Output: 2 45 56 Approach 1: Mainta 15+ min read In-Place Merge Sort | Set 2Given an array A[] of size N, the task is to sort the array in increasing order using In-Place Merge Sort. Examples: Input: A = {5, 6, 3, 2, 1, 6, 7}Output: {1, 2, 3, 5, 6, 6, 7} Input: A = {2, 3, 4, 1}Output: {1, 2, 3, 4} Approach: The idea is to use the inplace_merge() function to merge the sorted 7 min read Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 10 min read Merge Sort in Linked ListMerge Sort for Linked ListsGiven a singly linked list, The task is to sort the linked list in non-decreasing order using merge sort.Examples: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULLInput: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 - 12 min read Merge Sort for Doubly Linked ListGiven a doubly linked list, The task is to sort the doubly linked list in non-decreasing order using merge sort.Examples:Input: 10 <-> 8 <-> 4 <-> 2Output: 2 <-> 4 <-> 8 <-> 10Input: 5 <-> 3 <-> 2Output: 2 <-> 3 <-> 5 Note: Merge sort for a 13 min read Iterative Merge Sort for Linked ListGiven a singly linked list of integers, the task is to sort it using iterative merge sort.Examples:Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULLInput: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 -> 5 -> 8 - 13 min read Merge two sorted lists (in-place)Given two sorted linked lists consisting of n and m nodes respectively. The task is to merge both of the lists and return the head of the merged list.Example:Input: Output: Input: Output: Approach:The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A 9 min read Merge K sorted Doubly Linked List in Sorted OrderGiven K sorted doubly linked list. The task is to merge all sorted doubly linked list in single sorted doubly linked list means final list must be sorted.Examples: Input: List 1 : 2 <-> 7 <-> 8 <-> 12 <-> 15 <-> NULL List 2 : 4 <-> 9 <-> 10 <-> NULL Li 15+ min read Merge a linked list into another linked list at alternate positionsGiven 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 Find a permutation that causes worst case of Merge Sort Given a set of elements, find which permutation of these elements would result in worst case of Merge Sort.Asymptotically, merge sort always takes O(n Log n) time, but the cases that require more comparisons generally take more time in practice. We basically need to find a permutation of input eleme 12 min read How to make Mergesort to perform O(n) comparisons in best case? As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all thr 3 min read Concurrent Merge Sort in Shared Memory Given a number 'n' and a n numbers, sort the numbers using Concurrent Merge Sort. (Hint: Try to use shmget, shmat system calls).Part1: The algorithm (HOW?) Recursively make two child processes, one for the left half, one of the right half. If the number of elements in the array for a process is less 10 min read Visualization of Merge SortSorting Algorithm Visualization : Merge SortThe human brain can easily process visuals instead of long codes to understand the algorithms. In this article, a program that program visualizes the Merge sort Algorithm has been implemented. The GUI(Graphical User Interface) is implemented using pygame package in python. Approach: An array of rand 3 min read Merge Sort Visualization in JavaScriptGUI(Graphical User Interface) helps users with better understanding programs. In this article, we will visualize Merge Sort using JavaScript. We will see how the arrays are divided and merged after sorting to get the final sorted array. Refer: Merge SortCanvas in HTMLAsynchronous Function in JavaSc 4 min read Visualize Merge sort Using Tkinter in PythonPrerequisites: Python GUI â tkinter In this article, we will create a GUI application that will help us to visualize the algorithm of merge sort using Tkinter in Python. Merge Sort is a popular sorting algorithm. It has a time complexity of N(logN) which is faster than other sorting algorithms like 5 min read Visualization of Merge sort using MatplotlibPrerequisites: Introduction to Matplotlib, Merge Sort Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the a 3 min read 3D Visualisation of Merge Sort using MatplotlibVisualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use matplotlib to plot bar graphs and animate them to represent the elements 3 min read Some problems on Merge SortCount Inversions of an ArrayGiven an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorted 15+ min read Count of smaller elements on right side of each element in an Array using Merge sortGiven an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array Examples: Input: arr[] = {6, 3, 7, 2} Output: 2, 1, 1, 0 Explanation: Smaller elements after 6 = 2 [3, 2] Smaller elements after 3 = 1 [2] Smaller elements a 12 min read Sort a nearly sorted (or K sorted) arrayGiven an array arr[] and a number k . The array is sorted in a way that every element is at max k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i - k to i + k where i is index in the given array. Our task is to completely s 6 min read Median of two Sorted Arrays of Different SizesGiven two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si 15+ min read Merge k Sorted ArraysGiven K sorted arrays, merge them and print the sorted output.Examples:Input: K = 3, arr = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}}Output: 0 1 2 3 4 5 6 7 8 9 10 11 Input: k = 4, arr = { {1}, {2, 4}, {3, 7, 9, 11}, {13} }Output: 1 2 3 4 7 9 11 13Table of ContentNaive - Concatenate all and SortU 15+ min read Merge K sorted arrays of different sizes | ( Divide and Conquer Approach )Given k sorted arrays of different length, merge them into a single array such that the merged array is also sorted.Examples: Input : {{3, 13}, {8, 10, 11} {9, 15}} Output : {3, 8, 9, 10, 11, 13, 15} Input : {{1, 5}, {2, 3, 4}} Output : {1, 2, 3, 4, 5} Let S be the total number of elements in all th 8 min read Merge K sorted linked listsGiven k sorted linked lists of different sizes, the task is to merge them all maintaining their sorted order.Examples: Input: Output: Merged lists in a sorted order where every element is greater than the previous element.Input: Output: Merged lists in a sorted order where every element is greater t 15+ min read Union and Intersection of two Linked List using Merge SortGiven two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two lists contains distinct node values.Note: The order of elements in output lists doesn't matter.Examples:Input: head1: 10 -> 15 - 15+ min read Sorting by combining Insertion Sort and Merge Sort algorithmsInsertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort ru 2 min read Find array with k number of merge sort callsGiven two numbers n and k, find an array containing values in [1, n] and requires exactly k calls of recursive merge sort function. Examples: Input : n = 3 k = 3 Output : a[] = {2, 1, 3} Explanation: Here, a[] = {2, 1, 3} First of all, mergesort(0, 3) will be called, which then sets mid = 1 and call 6 min read Difference of two Linked Lists using Merge sortGiven two Linked List, the task is to create a Linked List to store the difference of Linked List 1 with Linked List 2, i.e. the elements present in List 1 but not in List 2.Examples: Input: List1: 10 -> 15 -> 4 ->20, List2: 8 -> 4 -> 2 -> 10 Output: 15 -> 20 Explanation: In the 14 min read Like