-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39.swift
127 lines (100 loc) · 2.54 KB
/
39.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* 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 Solution {
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
var first:ListNode? = head
var newHead:ListNode?
var current:ListNode? = head
var previous:ListNode?
var count = 0
while current != nil {
count += 1
if count >= k {
let (_head, _tail) = self.reverse(first, k)
if newHead == nil {
newHead = _head
}
if let pv = previous {
pv.next = _head
}
previous = _tail
_tail!.next = first!.next
first = _tail!.next
current = _tail
count = 0
}
current = current!.next
}
if newHead == nil {
newHead = head
}
return newHead
}
func reverse (_ head: ListNode?, _ k: Int) -> (ListNode?, ListNode?) {
var first:ListNode? = head
let current:ListNode? = head
var next:ListNode? = head!.next
for _ in 1..<k {
current!.next = next!.next
next!.next = first
first = next
next = current!.next
}
return (first, current)
}
}
public class LinkedList {
fileprivate var head: ListNode?
private var tail: ListNode?
public var first: ListNode? {
return head
}
public func append(_ value: Int) {
let newNode = ListNode(value)
if let tailNode = tail {
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
}
}
func answer(_ result: ListNode?) {
var res:ListNode? = result
var ans:Array<Int> = []
while (res != nil) {
ans.append(res!.val)
res = res!.next
}
print(ans)
}
func data(_ elments: Array<Int>) -> ListNode? {
let data = LinkedList()
for element in elments {
data.append(element)
}
return data.first
}
func main() {
let solution = Solution()
var result:ListNode?
// case 1
result = solution.reverseKGroup(data([1,2,3,4,5]), 2)
answer(result)
// case 2
result = solution.reverseKGroup(data([1]), 2)
answer(result)
// case 3
result = solution.reverseKGroup(data([8,9,8,8,5,7,7,0,3,5]), 3)
answer(result)
}
main()