Merge a linked list at alternate positions

Last Updated : 24 May, 2026

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: 10 -> 9, head2: 6 -> 1 -> 2 -> 3 -> 4 -> 5

blobid0_1778757611
blobid1_1778757626

Output: head1: 10 -> 6 -> 9 -> 1, head2: 2 -> 3 -> 4 -> 5

blobid2_1778757660
blobid3_1778757681


Explanation: After inserting nodes of head2 alternately into head1, the modified lists become 10 -> 6 -> 9 -> 1 and 2 -> 3 -> 4 -> 5, as the remaining nodes of head2 cannot be inserted.

Input: head1: 1 -> 2 -> 3, head2: 4 -> 5 -> 6

blobid0_1778757988
blobid1_1778758017

Output: head1: 1 -> 4 -> 2 -> 5 -> 3 -> 6, head2: <empty>

blobid2_1778758046

Explanation: After inserting nodes of head2 alternately into head1, the merged list becomes 1 -> 4 -> 2 -> 5 -> 3 -> 6, and head2 becomes empty as all its nodes are used.

Try It Yourself
redirect icon

Using Extra Array - O(n1 + n2) Time O(n2) Space

The idea is to first store all nodes of the second linked list in an array. Then, traverse the first list and insert nodes from the array one by one at alternate positions.

  • Traverse the second list and store its nodes in an array.
  • Traverse the first list.
  • Insert one stored node after every node of the first list.
  • If nodes of the second list remain, keep them as the second list.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// Function to print linked list
void printList(Node *head)
{

    Node *curr = head;

    while (curr != nullptr)
    {

        cout << curr->data;

        if (curr->next != nullptr)
            cout << " -> ";

        curr = curr->next;
    }

    cout << endl;
}

// Function to merge two linked lists
vector<Node *> mergeList(Node *head1, Node *head2)
{

    // Vector to store nodes of second list
    vector<Node *> arr;

    Node *temp = head2;

    // Store all nodes of second list
    while (temp != nullptr)
    {
        arr.push_back(temp);
        temp = temp->next;
    }

    Node *curr1 = head1;
    int i = 0;

    // Insert nodes at alternate positions
    while (curr1 != nullptr && i < arr.size())
    {

        // Store next pointers
        Node *next1 = curr1->next;
        Node *next2 = arr[i]->next;

        // Insert node from second list
        curr1->next = arr[i];
        arr[i]->next = next1;

        // Move to next node
        curr1 = next1;

        // Update remaining second list
        arr[i] = next2;

        i++;
    }

    // Remaining nodes of second list
    Node *rem = nullptr;

    if (i < arr.size())
        rem = arr[i];

    return {head1, rem};
}

// Driver Code
int main()
{

    // Creating first linked list: 10->9
    Node *head1 = new Node(10);
    head1->next = new Node(9);

    // Creating second linked list: 6->1->2->3->4->5
    Node *head2 = new Node(6);
    head2->next = new Node(1);
    head2->next->next = new Node(2);
    head2->next->next->next = new Node(3);
    head2->next->next->next->next = new Node(4);
    head2->next->next->next->next->next = new Node(5);

    vector<Node *> ans = mergeList(head1, head2);

    cout << "head1: ";
    printList(ans[0]);

    cout << "head2: ";
    printList(ans[1]);

    return 0;
}
Java
// Java program to merge a linked list into another
// at alternate positions using extra space

import java.util.*;

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to print linked list
    static void printList(Node head) {

        Node curr = head;

        while (curr != null) {

            System.out.print(curr.data);

            if (curr.next != null)
                System.out.print(" -> ");

            curr = curr.next;
        }

        System.out.println();
    }

    // Function to merge two linked lists
    static Node[] mergeList(Node head1, Node head2) {

        // ArrayList to store nodes of second list
        ArrayList<Node> arr = new ArrayList<>();

        Node temp = head2;

        // Store all nodes of second list
        while (temp != null) {
            arr.add(temp);
            temp = temp.next;
        }

        Node curr1 = head1;
        int i = 0;

        // Insert nodes at alternate positions
        while (curr1 != null && i < arr.size()) {

            // Store next pointers
            Node next1 = curr1.next;
            Node next2 = arr.get(i).next;

            // Insert node from second list
            curr1.next = arr.get(i);
            arr.get(i).next = next1;

            // Move to next node
            curr1 = next1;

            // Update remaining second list
            arr.set(i, next2);

            i++;
        }

        // Remaining nodes of second list
        Node rem = null;

        if (i < arr.size())
            rem = arr.get(i);

        return new Node[]{head1, rem};
    }

    // Driver Code
    public static void main(String[] args) {

        // Creating first linked list: 10->9
        Node head1 = new Node(10);
        head1.next = new Node(9);

        // Creating second linked list: 6->1->2->3->4->5
        Node head2 = new Node(6);
        head2.next = new Node(1);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(3);
        head2.next.next.next.next = new Node(4);
        head2.next.next.next.next.next = new Node(5);

        Node[] ans = mergeList(head1, head2);

        System.out.print("head1: ");
        printList(ans[0]);

        System.out.print("head2: ");
        printList(ans[1]);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to print linked list
def print_list(head):
    curr = head
    while curr is not None:
        print(curr.data, end="")
        if curr.next is not None:
            print(" -> ", end="")
        curr = curr.next
    print()

# Function to merge two linked lists
def merge_list(head1, head2):
    # List to store nodes of second list
    arr = []
    temp = head2

    # Store all nodes of second list
    while temp is not None:
        arr.append(temp)
        temp = temp.next

    curr1 = head1
    i = 0

    # Insert nodes at alternate positions
    while curr1 is not None and i < len(arr):
        # Store next pointers
        next1 = curr1.next
        next2 = arr[i].next

        # Insert node from second list
        curr1.next = arr[i]
        arr[i].next = next1

        # Move to next node
        curr1 = next1

        # Update remaining second list
        arr[i] = next2
        i += 1

    # Remaining nodes of second list
    rem = None
    if i < len(arr):
        rem = arr[i]

    return [head1, rem]

# Driver Code
if __name__ == "__main__":
    # Creating first linked list: 10->9
    head1 = Node(10)
    head1.next = Node(9)

    # Creating second linked list: 6->1->2->3->4->5
    head2 = Node(6)
    head2.next = Node(1)
    head2.next.next = Node(2)
    head2.next.next.next = Node(3)
    head2.next.next.next.next = Node(4)
    head2.next.next.next.next.next = Node(5)

    ans = merge_list(head1, head2)

    print("head1: ", end="")
    print_list(ans[0])

    print("head2: ", end="")
    print_list(ans[1])
C#
// C# program to merge a linked list into another
// at alternate positions using extra space

using System;
using System.Collections.Generic;

class Node
{
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

class GfG
{
    // Function to print linked list
    static void PrintList(Node head)
    {
        Node curr = head;

        while (curr != null)
        {
            Console.Write(curr.data);

            if (curr.next != null)
                Console.Write(" -> ");

            curr = curr.next;
        }

        Console.WriteLine();
    }

    // Function to merge two linked lists
    static Node[] MergeList(Node head1, Node head2)
    {
        // List to store nodes of second list
        List<Node> arr = new List<Node>();

        Node temp = head2;

        // Store all nodes of second list
        while (temp != null)
        {
            arr.Add(temp);
            temp = temp.next;
        }

        Node curr1 = head1;
        int i = 0;

        // Insert nodes at alternate positions
        while (curr1 != null && i < arr.Count)
        {
            // Store next pointers
            Node next1 = curr1.next;
            Node next2 = arr[i].next;

            // Insert node from second list
            curr1.next = arr[i];
            arr[i].next = next1;

            // Move to next node
            curr1 = next1;

            // Update remaining second list
            arr[i] = next2;

            i++;
        }

        // Remaining nodes of second list
        Node rem = null;

        if (i < arr.Count)
            rem = arr[i];

        return new Node[] { head1, rem };
    }

    // Driver Code
    static void Main()
    {
        // Creating first linked list: 10->9
        Node head1 = new Node(10);
        head1.next = new Node(9);

        // Creating second linked list: 6->1->2->3->4->5
        Node head2 = new Node(6);
        head2.next = new Node(1);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(3);
        head2.next.next.next.next = new Node(4);
        head2.next.next.next.next.next = new Node(5);

        Node[] ans = MergeList(head1, head2);

        Console.Write("head1: ");
        PrintList(ans[0]);

        Console.Write("head2: ");
        PrintList(ans[1]);
    }
}
JavaScript
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

// Function to print linked list
function printList(head) {
  let curr = head;
  while (curr!== null) {
    console.log(curr.data);
    if (curr.next!== null) {
      process.stdout.write(' -> ');
    }
    curr = curr.next;
  }
  console.log('\n');
}

// Function to merge two linked lists
function mergeList(head1, head2) {
  // Array to store nodes of second list
  let arr = [];
  let temp = head2;
  // Store all nodes of second list
  while (temp!== null) {
    arr.push(temp);
    temp = temp.next;
  }
  let curr1 = head1;
  let i = 0;
  // Insert nodes at alternate positions
  while (curr1!== null && i < arr.length) {
    // Store next pointers
    let next1 = curr1.next;
    let next2 = arr[i].next;
    // Insert node from second list
    curr1.next = arr[i];
    arr[i].next = next1;
    // Move to next node
    curr1 = next1;
    // Update remaining second list
    arr[i] = next2;
    i++;
  }
  // Remaining nodes of second list
  let rem = null;
  if (i < arr.length) {
    rem = arr[i];
  }
  return [head1, rem];
}

// Driver Code
// Creating first linked list: 10->9
let head1 = new Node(10);
head1.next = new Node(9);

// Creating second linked list: 6->1->2->3->4->5
let head2 = new Node(6);
head2.next = new Node(1);
head2.next.next = new Node(2);
head2.next.next.next = new Node(3);
head2.next.next.next.next = new Node(4);
head2.next.next.next.next.next = new Node(5);

let ans = mergeList(head1, head2);
console.log('head1: ');
printList(ans[0]);
console.log('head2: ');
printList(ans[1]);

Output
head1: 10 -> 6 -> 9 -> 1
head2: 2 -> 3 -> 4 -> 5

Time Complexity: O(n1 + n2), traversing second linked list and storing nodes in vector takes O(n2) time,
and traversing first linked list for insertion takes O(min(n1, n2)) time.
Auxiliary Space: O(n2)

Using Iterative Method – O(min(n1, n2)) Time 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.

  • Initialize two pointers to traverse the first and second linked lists.
  • Traverse both linked lists simultaneously until one of them becomes empty.
  • For every node of the first list, store the next nodes of both lists before changing links.
  • Insert the current node of the second list after the current node of the first list.
  • Move both pointers forward and continue the process. Remaining nodes of the second list stay unchanged.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// Function to print linked list
void printList(Node *head)
{

    Node *curr = head;

    while (curr != nullptr)
    {

        cout << curr->data;

        if (curr->next != nullptr)
            cout << " -> ";

        curr = curr->next;
    }

    cout << endl;
}

// Function to merge two linked lists
vector<Node *> mergeList(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 != nullptr && curr2 != nullptr)
    {

        // Save the next nodes of the current
        // nodes in both lists
        Node *ptr1 = curr1->next;
        Node *ptr2 = curr2->next;

        // Insert the current node from second list
        // after the current node from first list
        curr2->next = curr1->next;
        curr1->next = curr2;

        // Update the pointers for next iteration
        curr1 = ptr1;
        curr2 = ptr2;
    }

    return {head1, curr2};
}

// Driver Code
int main()
{

    // Creating first linked list: 10->9
    Node *head1 = new Node(10);
    head1->next = new Node(9);

    // Creating second linked list: 6->1->2->3->4->5
    Node *head2 = new Node(6);
    head2->next = new Node(1);
    head2->next->next = new Node(2);
    head2->next->next->next = new Node(3);
    head2->next->next->next->next = new Node(4);
    head2->next->next->next->next->next = new Node(5);

    vector<Node *> ans = mergeList(head1, head2);

    cout << "head1: ";
    printList(ans[0]);

    cout << "head2: ";
    printList(ans[1]);

    return 0;
}
Java
class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to print linked list
    public static void printList(Node head) {
        Node curr = head;

        while (curr != null) {
            System.out.print(curr.data);

            if (curr.next != null)
                System.out.print(" -> ");

            curr = curr.next;
        }

        System.out.println();
    }

    // Function to merge two linked lists
    public static Node[] mergeList(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
            Node ptr1 = curr1.next;
            Node ptr2 = curr2.next;

            // Insert node from second list
            curr2.next = curr1.next;
            curr1.next = curr2;

            // Move pointers
            curr1 = ptr1;
            curr2 = ptr2;
        }

        return new Node[] {head1, curr2};
    }

    // Driver Code
    public static void main(String[] args) {

        // Creating first linked list: 10->9
        Node head1 = new Node(10);
        head1.next = new Node(9);

        // Creating second linked list: 6->1->2->3->4->5
        Node head2 = new Node(6);
        head2.next = new Node(1);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(3);
        head2.next.next.next.next = new Node(4);
        head2.next.next.next.next.next = new Node(5);

        Node[] ans = mergeList(head1, head2);

        System.out.print("head1: ");
        printList(ans[0]);

        System.out.print("head2: ");
        printList(ans[1]);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to print linked list
def print_list(head):
    curr = head
    while curr is not None:
        print(curr.data, end="")
        if curr.next is not None:
            print(" -> ", end="")
        curr = curr.next
    print()

# Function to merge two linked lists
def merge_list(head1, head2):
    # Initialize pointers to traverse the two lists
    curr1 = head1
    curr2 = head2

    # Traverse both lists and merge them
    while curr1 is not None and curr2 is not None:
        # Save the next nodes of the current
        # nodes in both lists
        ptr1 = curr1.next
        ptr2 = curr2.next

        # Insert the current node from second list
        # after the current node from first list
        curr2.next = curr1.next
        curr1.next = curr2

        # Update the pointers for next iteration
        curr1 = ptr1
        curr2 = ptr2

    return [head1, curr2]

# Driver Code
if __name__ == "__main__":
    # Creating first linked list: 10->9
    head1 = Node(10)
    head1.next = Node(9)

    # Creating second linked list: 6->1->2->3->4->5
    head2 = Node(6)
    head2.next = Node(1)
    head2.next.next = Node(2)
    head2.next.next.next = Node(3)
    head2.next.next.next.next = Node(4)
    head2.next.next.next.next.next = Node(5)

    ans = merge_list(head1, head2)

    print("head1: ", end="")
    print_list(ans[0])

    print("head2: ", end="")
    print_list(ans[1])
C#
using System;
using System.Collections.Generic;

public class Node
{
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class GfG
{
    // Function to print linked list
    public static void printList(Node head)
    {
        Node curr = head;

        while (curr != null)
        {
            Console.Write(curr.data);

            if (curr.next != null)
                Console.Write(" -> ");

            curr = curr.next;
        }

        Console.WriteLine();
    }

    // Function to merge two linked lists
    public static List<Node> mergeList(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
            Node ptr1 = curr1.next;
            Node ptr2 = curr2.next;

            // Insert node from second list
            curr2.next = curr1.next;
            curr1.next = curr2;

            // Move pointers
            curr1 = ptr1;
            curr2 = ptr2;
        }

        return new List<Node> { head1, curr2 };
    }

    // Driver Code
    public static void Main()
    {
        // Creating first linked list: 10->9
        Node head1 = new Node(10);
        head1.next = new Node(9);

        // Creating second linked list: 6->1->2->3->4->5
        Node head2 = new Node(6);
        head2.next = new Node(1);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(3);
        head2.next.next.next.next = new Node(4);
        head2.next.next.next.next.next = new Node(5);

        List<Node> ans = mergeList(head1, head2);

        Console.Write("head1: ");
        printList(ans[0]);

        Console.Write("head2: ");
        printList(ans[1]);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}

// Function to print linked list
function printList(head)
{
    let curr = head;

    while (curr !== null) {
        process.stdout.write(curr.data.toString());

        if (curr.next !== null)
            process.stdout.write(" -> ");

        curr = curr.next;
    }

    console.log();
}

// Function to merge two linked lists
function mergeList(head1, head2)
{

    // Initialize pointers to traverse the two lists
    let curr1 = head1;
    let curr2 = head2;

    // Traverse both lists and merge them
    while (curr1 !== null && curr2 !== null) {

        // Save the next nodes
        let ptr1 = curr1.next;
        let ptr2 = curr2.next;

        // Insert node from second list
        curr2.next = curr1.next;
        curr1.next = curr2;

        // Move pointers
        curr1 = ptr1;
        curr2 = ptr2;
    }

    return [ head1, curr2 ];
}

// Driver Code

// Creating first linked list: 10->9
let head1 = new Node(10);
head1.next = new Node(9);

// Creating second linked list: 6->1->2->3->4->5
let head2 = new Node(6);
head2.next = new Node(1);
head2.next.next = new Node(2);
head2.next.next.next = new Node(3);
head2.next.next.next.next = new Node(4);
head2.next.next.next.next.next = new Node(5);

let ans = mergeList(head1, head2);

process.stdout.write("head1: ");
printList(ans[0]);

process.stdout.write("head2: ");
printList(ans[1]);

Output
head1: 10 -> 6 -> 9 -> 1
head2: 2 -> 3 -> 4 -> 5

Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists.
Auxiliary Space: O(1).

Comment