-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0025-reverse-nodes-in-k-group.swift
57 lines (47 loc) · 1.42 KB
/
0025-reverse-nodes-in-k-group.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
50
51
52
53
54
55
56
57
/**
* Question Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class ReverseKGroup {
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
var dummy = ListNode(0, head)
var groupPrev: ListNode? = dummy
while true {
let kth = getKth(current: groupPrev, k: k)
if kth == nil {
break
}
let groupNext = kth?.next
var prev = kth?.next
var current = groupPrev?.next
while current !== groupNext {
let temp = current?.next
current?.next = prev
prev = current
current = temp
}
let temp = groupPrev?.next
groupPrev?.next = kth
groupPrev = temp
}
return dummy.next
}
func getKth(current: ListNode?, k: Int) -> ListNode? {
var current = current
var k = k
while current != nil && k > 0 {
current = current?.next
k -= 1
}
return current
}
}