-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.js
133 lines (105 loc) · 2.42 KB
/
linkedList.js
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
function LinkedList(){
this.head = null;
}
function Node(data){
this.data = data;
this.next = null;
}
LinkedList.prototype.push = function(data){
if(!this.head){
this.head = new Node(data);
}
else {//iterating to the end
var current = this.head;
while(current && current.next){
current = current.next;
}
current.next = new Node(data);
}
}
LinkedList.prototype.print = function(){
var current = this.head;
while(current){
console.log(current.data);
current = current.next;
}
}
function Merge(list1, list2){
debugger;
console.log("Inside the merged list");
var mergedList = new LinkedList();
var leftPtr = list1.head;
var rightPtr = list2.head;
/**
*@desc: method to copy the node data and move the point to next location
*@return: next refernce
*/
var cloneAndMove = function(node){
mergedList.push(node.data);
return node.next;
}
while(leftPtr && rightPtr){
if(leftPtr.data < rightPtr.data){
leftPtr = cloneAndMove(leftPtr);
}
else{
rightPtr = cloneAndMove(rightPtr);
}
}
while(leftPtr){
leftPtr = cloneAndMove(leftPtr);
}
while(rightPtr){
rightPtr = cloneAndMove(rightPtr);
}
return mergedList;
}
function MergeSort(list) {
var partitionList = function(list){
var slowPtr,fastPtr;
//empty linked list/list with one element
if(!list || !list.head){
return {left: null, right: null};
}
slowPtr = list.head;
fastPtr = list.head;
var leftList = new LinkedList();
var rightList = new LinkedList();
while(fastPtr.next){
if(fastPtr.next && fastPtr.next.next){
//copying the data
leftList.push(slowPtr.data);
fastPtr = fastPtr.next.next;
slowPtr = slowPtr.next;
}
else{
//copying the data
leftList.push(slowPtr.data);
slowPtr = slowPtr.next;
fastPtr = fastPtr.next;
}
}
while(slowPtr){
rightList.push(slowPtr.data);
slowPtr = slowPtr.next;
}
return response ={ left: leftList, right: rightList };
}
//empty list/ list with one node already sorted
if(!list && !list.head && !list.head.next){
return list;
}
else {
var leftList = null, rightList = null;
var partition = partitionList(list);
leftList = partition.left;
rightList = partition.right;
if(leftList && leftList.head.next){
leftList = MergeSort(leftList);
}
if(rightList && rightList.head.next){
rightList = MergeSort(rightList);
}
return Merge(leftList, rightList);
}
}