forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReorderList.swift
67 lines (54 loc) · 1.55 KB
/
ReorderList.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
/**
* Question Link: https://leetcode.com/problems/reorder-list/
* Primary idea: Use Runner Tech to split the list, reverse the second half, and merge them
* 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 ReorderList {
func reorderList(head: ListNode?) {
if head == nil || head!.next == nil {
return
}
// split the list
var prev = head
var post = head!.next
while post != nil && post!.next != nil {
prev = prev!.next
post = post!.next!.next
}
post = prev!.next
prev!.next = nil
prev = head
// reverse the second list
post = _reverse(post)
// merge lists
while prev != nil && post != nil{
let preNext = prev!.next
let posNext = post!.next
prev!.next = post
post!.next = preNext
prev = preNext
post = posNext
}
}
private func _reverse(head: ListNode?) -> ListNode?{
var prev = head
var temp: ListNode?
while prev != nil {
let post = prev!.next
prev!.next = temp
temp = prev
prev = post
}
return temp
}
}