-
Notifications
You must be signed in to change notification settings - Fork 889
/
ReverseNodesInKGroup.swift
49 lines (44 loc) · 1.69 KB
/
ReverseNodesInKGroup.swift
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
/**
* Question Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
* Primary idea: Reverse one group during one loop. Construct a reversed group from back to forth.
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class ReverseNodesInKGroup {
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var prev = dummy // prev = A
while prev.next != nil { // A->B->C->D->E => A->D->C->B->E
var groupTail : ListNode? = prev
for _ in 1...k {
groupTail = groupTail?.next
}
guard let _ = groupTail else { // groupTail = D
break
}
let nextGroupHead = groupTail!.next // nextGroupHead = E
var last = nextGroupHead // last = E
var current : ListNode? = prev.next // current = B
while current != nil && current !== nextGroupHead {
let next = current!.next // next = C
current!.next = last // B -> E
last = current // last = B
current = next // current = C
}
groupTail = prev.next
prev.next = last
prev = groupTail!
}
return dummy.next
}
}