4-Merge Sort For DLL-08!01!2024

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

Merge two sorted list

Merge two sorted list


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.

Input:

5
67 78 89 100 123
4
12 24 34 45

Output:

Merged Linked List is


12 24 34 45 67 78 89 100 123
1 import java.util.*;
2 class Node {
3 int data;
4 Node next;
5 Node(int d){
6 data = d;
7 next = null;
8 }
9 }
10 class MergeLists {
11 Node head;
12 public void addToTheLast(Node node){
13 if (head == null)
14 head = node;
15 else {
16 Node temp = head;
17 while (temp.next != null)
18 temp = temp.next;
19 temp.next = node;
20 }
21 }
22
23 void printList(){
24 Node temp = head;
25 while (temp != null) {
26 System.out.print(temp.data + " ");
27 temp = temp.next;
28 }
29 System.out.println();
30 }
31 public static void main(String args[]){
32 Scanner s=new Scanner(System.in);
33 MergeLists llist1 = new MergeLists();
34 MergeLists llist2 = new MergeLists();
35 int n=s.nextInt();
36 for(int i=0; i<n; i++)
37 llist1.addToTheLast(new Node(s.nextInt()));
38 int m=s.nextInt();
39 for(int i=0; i<m; i++)
40 llist2.addToTheLast(new Node(s.nextInt()));
41 llist1.head = new sol().sortedMerge(llist1.head,llist2.head);
42 System.out.println("Merged Linked List is:");
43 llist1.printList();
44 }}
45 class sol {
46 public Node sortedMerge(Node list1, Node list2){
47 Node li1 = list1, li2 = list2;
48 Node dummy = new Node(0);
49 Node temp = dummy;
50 if(list1 == null)
51 return list2;
52 if(list2 == null)
53 return list1;
54 while(li1 != null && li2 != null){
55 if(li1.data < li2.data){
56 temp.next = li1;
57 li1 = li1.next;
58 }else{
59 temp.next = li2;
60 li2 = li2.next;
61 }temp = temp.next;}
62 if(li1 != null) temp.next = li1;
63 if(li2 != null)temp.next = li2;
64 return dummy.next;
65 }
66 }
THANK YOU

You might also like