-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathflattenLinkedList.js
More file actions
119 lines (90 loc) · 2.33 KB
/
Copy pathflattenLinkedList.js
File metadata and controls
119 lines (90 loc) · 2.33 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
<script>
var head; // head of list
/* Linked list Node */
class Node {
constructor(val) {
this.data = val;
this.down = null;
this.next = null;
}
}
// An utility function to merge two sorted linked lists
function merge(a, b) {
// if first linked list is empty then second
// is the answer
if (a == null)
return b;
// if second linked list is empty then first
// is the result
if (b == null)
return a;
// compare the data members of the two linked lists
// and put the larger one in the result
var result;
if (a.data < b.data) {
result = a;
result.down = merge(a.down, b);
}
else {
result = b;
result.down = merge(a, b.down);
}
result.right = null;
return result;
}
function flatten(root) {
// Base Cases
if (root == null || root.right == null)
return root;
// recur for list on right
root.right = flatten(root.right);
// now merge
root = merge(root, root.right);
// return the root
// it will be in turn merged with its left
return root;
}
/*
* Utility function to insert a node at beginning of the linked list
*/
function push(head_ref , data) {
/*
* 1 & 2: Allocate the Node & Put in the data
*/
var new_node = new Node(data);
/* 3. Make next of new Node as head */
new_node.down = head_ref;
/* 4. Move the head to point to new Node */
head_ref = new_node;
/* 5. return to link it back */
return head_ref;
}
function printList() {
var temp = head;
while (temp != null) {
document.write(temp.data + " ");
temp = temp.down;
}
document.write();
}
/*
* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7
* 20 22 35 | | | V V V 8 50 40 | | V V 30 45
*/
head = push(head, 30);
head = push(head, 8);
head = push(head, 7);
head = push(head, 5);
head.right = push(head.right, 20);
head.right = push(head.right, 10);
head.right.right = push(head.right.right, 50);
head.right.right = push(head.right.right, 22);
head.right.right = push(head.right.right, 19);
head.right.right.right = push(head.right.right.right, 45);
head.right.right.right = push(head.right.right.right, 40);
head.right.right.right = push(head.right.right.right, 35);
head.right.right.right = push(head.right.right.right, 20);
// flatten the list
head = flatten(head);
printList();
</script>