-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0143-reorder-list.swift
73 lines (64 loc) · 1.76 KB
/
0143-reorder-list.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
// Slow and Fast Pointer Method
/**
* Question Link: https://leetcode.com/problems/reorder-list/
*/
/**
* 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 ReorderList {
func reorderList(_ head: ListNode?) {
var slow = head
var fast = head?.next
while fast != nil || fast?.next != nil {
slow = slow?.next
fast = fast?.next?.next
}
var second = slow?.next
slow?.next = nil
var prev: ListNode?
while second != nil {
var temp = second?.next
second?.next = prev
prev = second
second = temp
}
var first = head
second = prev
while second != nil {
var temp1 = first?.next
var temp2 = second?.next
first?.next = second
second?.next = temp1
first = temp1
second = temp2
}
}
}
// Deque
import DequeModule
class Solution {
func reorderList(_ head: ListNode?) {
var queue = Deque<ListNode>()
var curr = head
while curr != nil {
queue.append(curr!)
curr = curr!.next
}
var lastNode: ListNode?
while !queue.isEmpty {
let leftNode = queue.popFirst()
let rightNode = queue.popLast()
rightNode?.next = nil
leftNode?.next = rightNode
lastNode?.next = leftNode
lastNode = rightNode
}
}
}