forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReorderList.swift
72 lines (57 loc) · 1.63 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
68
69
70
71
72
/**
* 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?) {
guard let head = head else {
return
}
var prev: ListNode? = head
var post: ListNode? = head
_split(&prev, &post)
prev = head
post = _reverse(&post)
_merge(&prev, &post)
}
private func _split(inout prev: ListNode?, inout _ post: ListNode?) {
while post != nil && post!.next != nil {
prev = prev!.next
post = post!.next!.next
}
post = prev!.next
prev!.next = nil
}
private func _reverse(inout 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
}
private func _merge(inout prev: ListNode?, inout _ post: ListNode?) {
while prev != nil && post != nil{
let preNext = prev!.next
let posNext = post!.next
prev!.next = post
post!.next = preNext
prev = preNext
post = posNext
}
}
}