• Register
Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Merge a linked list into another linked list at alternate positions in java

0 votes
36 views
Merge a linked list into another linked list at alternate positions in java.
list1 = 1 2 7 3 9
list2 = 6 10 2 4 6
Merged at alternate position list:
1 6 2 10 7 2 3 4 9 6
asked Feb 5 in Data Structure And Algorithm by Jitendra Prajapati

1 Answer

0 votes
See the following running example to merge linked list into another linked list at alternate positions in java.

package com.ds.linkedlist;

public class MergeAlternateList {

    Node head;
    public static void main(String[] args) {
        MergeAlternateList list1 = new MergeAlternateList();
        list1.insert(5);
        list1.insert(7);
        list1.insert(17);
        list1.insert(13);
        list1.insert(11);
       
        MergeAlternateList list2 = new MergeAlternateList();
        list2.insert(12);
        list2.insert(10);
        list2.insert(2);
        list2.insert(4);
        list2.insert(6);
       
        System.out.println("List1: ");
        list1.print();
        System.out.println("\nList2: ");
        list2.print();
       
        MergeAlternateList mlist = new MergeAlternateList();
        mlist.mergeAlternateList(list1.head, list2.head);
        System.out.println("\nMerged Alternate Lists1 and List2: ");
        mlist.print();
    }
   
    private void mergeAlternateList(Node list1, Node list2) {
        Node l1 = list1, l2 = list2;
        Node l1_next = null, l2_next = null;
        while(l1 != null && l2 != null){
            l1_next = l1.next;
            l2_next = l2.next;
           
            l2.next = l1_next;
            l1.next = l2;
           
           
            l1 = l1_next;
            l2 = l2_next;
        }
        this.head = list1;
       
    }

    private class Node{
        int data;
        Node next;
        Node(int data){
            this.data = data;
        }
    }
   
    public void insert(int data){
        Node newNode = new Node(data);
        if(head == null){
            head = newNode;
        }else{
            Node curr = head;
            while(curr.next != null){
                curr = curr.next;
            }
            curr.next = newNode;
        }
    }
   
    public void print(){
        if(head==null)
            return;
        Node curr = head;
        while(curr != null){
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
    }

}
Output:-
List1:
5 7 17 13 11
List2:
12 10 2 4 6
Merged Alternate Lists1 and List2:
5 12 7 10 17 2 13 4 11 6
answered Feb 8 by ranju_12 (1,740 points)
...