forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateList.swift
56 lines (47 loc) · 1.16 KB
/
RotateList.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
/**
* Question Link: https://leetcode.com/problems/rotate-list/
* Primary idea: Runner Tech
* 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 RotateList {
func rotateRight(head: ListNode?, _ k: Int) -> ListNode? {
if head == nil {
return head
}
var prev = head
var post = head
let len = _getLength(head)
var k = k % len
while k > 0 {
post = post!.next
k -= 1
}
while post!.next != nil {
prev = prev!.next
post = post!.next
}
post!.next = head
post = prev!.next
prev!.next = nil
return post
}
private func _getLength(head: ListNode?) -> Int {
var len = 0
var node = head
while node != nil {
len += 1
node = node!.next
}
return len
}
}