@@ -28,3 +28,88 @@ const reverseKGroup = function(head, k) {
28
28
}
29
29
return dmy . next
30
30
}
31
+
32
+ // another
33
+
34
+ /**
35
+ * Definition for singly-linked list.
36
+ * function ListNode(val, next) {
37
+ * this.val = (val===undefined ? 0 : val)
38
+ * this.next = (next===undefined ? null : next)
39
+ * }
40
+ */
41
+ /**
42
+ * @param {ListNode } head
43
+ * @param {number } k
44
+ * @return {ListNode }
45
+ */
46
+ const reverseKGroup = function ( head , k ) {
47
+ let ptr = head
48
+ let ktail = null
49
+
50
+ // Head of the final, moified linked list
51
+ let new_head = null
52
+
53
+ // Keep going until there are nodes in the list
54
+ while ( ptr != null ) {
55
+ let count = 0
56
+
57
+ // Start counting nodes from the head
58
+ ptr = head
59
+
60
+ // Find the head of the next k nodes
61
+ while ( count < k && ptr != null ) {
62
+ ptr = ptr . next
63
+ count += 1
64
+ }
65
+
66
+ // If we counted k nodes, reverse them
67
+ if ( count == k ) {
68
+ // Reverse k nodes and get the new head
69
+ let revHead = reverseLinkedList ( head , k )
70
+
71
+ // new_head is the head of the final linked list
72
+ if ( new_head == null ) new_head = revHead
73
+
74
+ // ktail is the tail of the previous block of
75
+ // reversed k nodes
76
+ if ( ktail != null ) ktail . next = revHead
77
+
78
+ ktail = head
79
+ head = ptr
80
+ }
81
+ }
82
+
83
+ // attach the final, possibly un-reversed portion
84
+ if ( ktail != null ) ktail . next = head
85
+
86
+ return new_head == null ? head : new_head
87
+ }
88
+
89
+ function reverseLinkedList ( head , k ) {
90
+ // Reverse k nodes of the given linked list.
91
+ // This function assumes that the list contains
92
+ // atleast k nodes.
93
+ let new_head = null
94
+ let ptr = head
95
+
96
+ while ( k > 0 ) {
97
+ // Keep track of the next node to process in the
98
+ // original list
99
+ let next_node = ptr . next
100
+
101
+ // Insert the node pointed to by "ptr"
102
+ // at the beginning of the reversed list
103
+ ptr . next = new_head
104
+ new_head = ptr
105
+
106
+ // Move on to the next node
107
+ ptr = next_node
108
+
109
+ // Decrement the count of nodes to be reversed by 1
110
+ k --
111
+ }
112
+
113
+ // Return the head of the reversed list
114
+ return new_head
115
+ }
0 commit comments