-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_a_sub_list.js
More file actions
53 lines (47 loc) · 1.27 KB
/
Copy pathreverse_a_sub_list.js
File metadata and controls
53 lines (47 loc) · 1.27 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
class Node {
constructor(value, next=null){
this.value = value;
this.next = next;
}
get_list() {
let result = "";
let temp = this;
while (temp !== null) {
result += temp.value + " ";
temp = temp.next;
}
return result;
}
};
const reverse_sub_list = function(head, p, q) {
let end_of_left_segment = head;
let i=1;
while (i<p-1) {
i++;
end_of_left_segment = end_of_left_segment.next;
}
let start_of_right_segment = null;
let previous = null;
let current = end_of_left_segment.next;
let j = p;
while (j <= q) {
j++;
let next = current.next;
current.next = previous;
previous = current;
current = next;
if (j==q) {
start_of_right_segment = current.next;
}
}
end_of_left_segment.next.next = current;
end_of_left_segment.next = previous;
return head;
};
head = new Node(1)
head.next = new Node(2)
head.next.next = new Node(3)
head.next.next.next = new Node(4)
head.next.next.next.next = new Node(5)
console.log(`Nodes of original LinkedList are: ${head.get_list()}`)
console.log(`Nodes of reversed LinkedList are: ${reverse_sub_list(head, 2, 4).get_list()}`)