1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * val: number
5
+ * next: ListNode | null
6
+ * constructor(val?: number, next?: ListNode | null) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.next = (next===undefined ? null : next)
9
+ * }
10
+ * }
11
+ */
12
+
13
+ /**
14
+ * Problem: Leet Code 25, Reverse Linked List K Nodes at a time.
15
+ * Solution: Uses an iterative approach to reverse linked list. Uses a modular function which can reverse the k nodes
16
+ * using an iterative approach. This approach uses last, curr and next pointer to keep on updating the pointers
17
+ * as we navigate. Additionally, it returns the new head, tail and next pointer in order to continue further. As it iterates,
18
+ * it just needs to modify the pointers along the way.
19
+ *
20
+ * time: O(n) as all nodes need one traversal, O(1) space.
21
+ *
22
+ * @param head
23
+ * @param k
24
+ */
25
+ function reverseKGroup ( head : ListNode | null , k : number ) : ListNode | null {
26
+
27
+ if ( head === null ) return null ;
28
+
29
+ const length = getLength ( head )
30
+ let next : ListNode | null = head , lastTail : ListNode | null = head ;
31
+ for ( let group = k ; group <= length && next !== null ; group += k ) {
32
+
33
+ // Reverse the subgroup, getting the group head and tail
34
+ const { groupHead, groupTail, groupNext} = reverseGroup ( next , k ) ;
35
+
36
+ // Adjust the head pointer of previous group or main head.
37
+ if ( group === k ) head = groupHead ;
38
+ else if ( lastTail !== null ) lastTail . next = groupHead ;
39
+
40
+ // Update the last tail to allow future updates.
41
+ lastTail = groupTail ;
42
+ next = groupNext ;
43
+ }
44
+
45
+ // Point for pending items
46
+ if ( lastTail !== null )
47
+ lastTail . next = next ;
48
+
49
+ return head ;
50
+ } ;
51
+
52
+ function reverseGroup ( head : ListNode | null , k : number ) : {
53
+ groupHead : ListNode | null ,
54
+ groupTail : ListNode | null ,
55
+ groupNext : ListNode | null
56
+ } {
57
+
58
+ let curr = head , last = null , next = null , count = 0 ;
59
+ while ( count < k && curr !== null ) {
60
+ next = curr . next
61
+ curr . next = last ;
62
+ last = curr ;
63
+ curr = next ;
64
+ count ++
65
+ }
66
+
67
+ return {
68
+ groupHead : last ,
69
+ groupTail : head ,
70
+ groupNext : next
71
+ }
72
+ }
73
+
74
+ function getLength ( head : ListNode | null ) {
75
+ let curr = head , length = 0 ;
76
+ while ( curr !== null ) {
77
+ curr = curr . next ;
78
+ length ++ ;
79
+ }
80
+
81
+ return length ;
82
+ }
0 commit comments