-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmergeTwoSortedLinkedList
135 lines (117 loc) · 2.17 KB
/
mergeTwoSortedLinkedList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/* Java program to merge two
sorted linked lists */
import java.util.*;
/* Link list node */
class Node
{
int data;
Node next;
Node(int d) {data = d;
next = null;}
}
class MergeLists
{
Node head;
/* Method to insert a node at
the end of the linked list */
public void addToTheLast(Node node)
{
if (head == null)
{
head = node;
}
else
{
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
/* Method to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Driver Code
public static void main(String args[])
{
/* Let us create two sorted linked
lists to test the methods
Created lists:
llist1: 5->10->15,
llist2: 2->3->20
*/
MergeLists llist1 = new MergeLists();
MergeLists llist2 = new MergeLists();
// Node head1 = new Node(5);
llist1.addToTheLast(new Node(5));
llist1.addToTheLast(new Node(10));
llist1.addToTheLast(new Node(15));
// Node head2 = new Node(2);
llist2.addToTheLast(new Node(2));
llist2.addToTheLast(new Node(3));
llist2.addToTheLast(new Node(20));
llist1.head = new Gfg().sortedMerge(llist1.head,
llist2.head);
llist1.printList();
}
}
class Gfg
{
/* Takes two lists sorted in
increasing order, and splices
their nodes together to make
one big sorted list which is
returned. */
Node sortedMerge(Node headA, Node headB)
{
/* a dummy first node to
hang the result on */
Node dummyNode = new Node(0);
/* tail points to the
last result node */
Node tail = dummyNode;
while(true)
{
/* if either list runs out,
use the other list */
if(headA == null)
{
tail.next = headB;
break;
}
if(headB == null)
{
tail.next = headA;
break;
}
/* Compare the data of the two
lists whichever lists' data is
smaller, append it into tail and
advance the head to the next Node
*/
if(headA.data <= headB.data)
{
tail.next = headA;
headA = headA.next;
}
else
{
tail.next = headB;
headB = headB.next;
}
/* Advance the tail */
tail = tail.next;
}
return dummyNode.next;
}
}
// This code is contributed
// by Shubhaw Kumar