-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedLists.java
More file actions
128 lines (103 loc) · 2.94 KB
/
Copy pathMergeSortedLists.java
File metadata and controls
128 lines (103 loc) · 2.94 KB
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
package LinkedList;
/**
* Created by rmukherj on 7/16/16.
*/
public class MergeSortedLists {
static Node head;
static class Node {
int data;
Node next;
public Node(){}
public Node(int d){
data = d;
next = null;
}
}
Node recursiveSortedMerge(Node current, Node prev){
Node result = null;
if(current == null){
return prev;
}
if(prev == null ){
return current;
}
if(current.data<=prev.data){
current.next = recursiveSortedMerge(current.next,prev);
return current;
} else {
prev.next = recursiveSortedMerge(prev.next, current);
return prev;
}
// return result;
}
void printList(Node node){
while(node != null){
System.out.println(node.data + " ");
node= node.next;
}
}
public Node mergeSort(Node current){
if(current == null || current.next == null){
return current;
}
Node a = current;
Node b = current.next;
while((b!=null) && (b.next!=null)){
current = current.next;
b = (b.next).next;
}
b = current.next;
current.next = null;
return merge(mergeSort(a),mergeSort(b));
}
public Node merge(Node a, Node b){
Node temp = new Node();
Node head = temp;
Node c = head;
while ((a != null) && (b != null))
{
if (a.data <= b.data)
{
c.next = a;
c = a;
a = a.next;
}
else
{
c.next = b;
c = b;
b = b.next;
}
}
c.next = (a == null) ? b : a;
return head.next;
}
public static void main(String[] args){
MergeSortedLists list = new MergeSortedLists();
list.head = new Node(8);
list.head.next = new Node(5);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(2);
MergeSortedLists list1 = new MergeSortedLists();
list.head = new Node(5);
list.head.next = new Node(3);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(1);
Node n = new Node(7);
n.next = new Node(4);
n.next.next = new Node(2);
n.next.next.next = new Node(1);
Node n1 = new Node(72);
n1.next = new Node(43);
n1.next.next = new Node(52);
n1.next.next.next = new Node(13);
System.out.println("Original Linked list is :");
// list.printList(head);
// head = list.recursiveSortedMerge(n,n1);
head = list.mergeSort(n);
list.printList(head);
System.out.println("");
// System.out.println("Reversed linked list : ");
// list.printList(head);
}
}