-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseLinkedList.js
94 lines (71 loc) · 1.88 KB
/
reverseLinkedList.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
function ListNode(val) {
this.val = val;
this.next = null;
}
const reverseKGroup = (head, k) => {
if (k === 1 || !head || !head.next) {
return head;
}
// defined pointer, a count variable, and a dummy node to attach first reversed linked list section to
let count;
let result = new ListNode(-1);
let res = result;
// iterate through linked list
while (head) {
// define additional pointers
let fakeHead = head;
let next = null;
count = 1;
// count k elements in linked list
while (head && count !== k) {
count += 1;
head = head.next;
}
// if there were k elements left in the linked list reverse
if (head && count === k) {
next = head.next;
head.next = null;
result.next = reverseList(fakeHead);
// move pointer to end of newly reversed linked list
while (result.next) {
result = result.next;
}
// move pointer to start of next linked list section
head = next;
// if there weren’t k elements left in the linked list move pointer to end of list
} else if (!head) {
while (result.next) {
result = result.next;
}
result.next = fakeHead;
}
}
// return linked list
return res.next;
};
const reverseList = head => {
let result = null;
let stack = [];
let current = head;
while (current) {
stack.push(current);
current = current.next;
}
result = stack.pop() || [];
current = result;
while (current) {
current.next = stack.pop();
current = current.next;
}
return result;
};
// a recursive option to reverse the linked list
const reverseListRecursive = (node, parent) => {
let result = parent || {};
if (node) {
let child = node.next;
node.next = parent;
result = reverseListRecursive(child, node);
}
return result;
}