-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathReverseALinkedListInGroupOfK.js
93 lines (86 loc) · 2.62 KB
/
ReverseALinkedListInGroupOfK.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
/**
* @author Anirudh Sharma
*
* Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function)
* in the linked list.
*/
const reverseKGroup = (head, k) => {
// Base condition
if (head === null || k === 1) {
return head;
}
// Dummy node before head
const dummy = new ListNode(-1);
// Point the next of this dummy to the current head
dummy.next = head;
// Node to keep track of the previous node
let previous = dummy;
// Variable to keep count of the nodes in the linked list
let count = 0;
// Reference to the head which will be used to traverse
let current = head;
while (current !== null) {
count++;
if (count % k === 0) {
previous = reverse(previous, current.next);
current = previous.next;
} else {
current = current.next;
}
}
return dummy.next;
};
const reverse = (start, end) => {
// Previous node of the current node
let previous = start.next;
// Current node
let current = previous.next;
// Next node of the current node
let next;
// Loop for the whole interval
while (current != end) {
// Next node of the current node
next = current.next;
// Next of current will point to the previous
current.next = start.next;
// Current node will become the previous node
start.next = current;
// Move pointer ahead
current = next;
}
previous.next = end;
// Return head node of the reversed linked list
return previous;
}
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
function printList(node) {
let list = [];
while (node != null) {
list.push(node.val);
node = node.next
}
console.log(list.join(" "));
}
let headNode = new ListNode(1);
headNode.next = new ListNode(2);
headNode.next.next = new ListNode(3);
headNode.next.next.next = new ListNode(4);
headNode.next.next.next.next = new ListNode(5);
printList(reverseKGroup(headNode, 2));
headNode = new ListNode(1);
headNode.next = new ListNode(2);
headNode.next.next = new ListNode(3);
headNode.next.next.next = new ListNode(4);
headNode.next.next.next.next = new ListNode(5);
printList(reverseKGroup(headNode, 3));
headNode = new ListNode(1);
headNode.next = new ListNode(2);
headNode.next.next = new ListNode(3);
headNode.next.next.next = new ListNode(4);
headNode.next.next.next.next = new ListNode(5);
printList(reverseKGroup(headNode, 1));
headNode = new ListNode(1);
printList(reverseKGroup(headNode, 1));