-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathreverseSubstring.js
111 lines (94 loc) · 2.44 KB
/
reverseSubstring.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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value) {
const newNode = new Node(value);
this.head = newNode;
this.head = newNode;
this.tail = newNode;
this.length = 1;
}
push(value) {
const newNode = new Node(value);
if(!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
reverseBetween(m, n) {
if (this.head === null) return;
const dummy = new Node(0);
dummy.next = this.head;
let prev = dummy;
for (let i = 0; i < m; i++) {
prev = prev.next;
}
let current = prev.next;
for (let i = 0; i < n - m; i++) {
const temp = current.next;
current.next = temp.next;
temp.next = prev.next;
prev.next = temp;
}
this.head = dummy.next;
}
reverseBetweenUsingReverseList(m, n) {
if(!this.head) return;
let current = this.head;
let revPrev = null;
let revBegin = null;
let revEnd = null;
let revEndNext = null;
let i = 0;
while(current && i <= n) {
if(i < m) {
revPrev = current;
}
if(i === m) {
revBegin = current;
}
if(i === n) {
revEnd = current;
revEndNext = current.next;
}
current = current.next;
i++;
}
revEnd.next = null;
revEnd = this.reverse(revBegin);
if(revPrev) {
revPrev.next = revEnd;
} else {
this.head = revEnd;
}
revBegin.next = revEndNext;
return this.head;
}
reverse(head) {
let current = head;
let prev = null;
while(current){
let next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
const myLinkedList = new LinkedList(1);
myLinkedList.push(2);
myLinkedList.push(3);
myLinkedList.push(4);
myLinkedList.push(5);
myLinkedList.reverseBetween(2, 4);
myLinkedList.reverseBetweenUsingReverseList(1, 3);