-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem232.swift
41 lines (36 loc) · 985 Bytes
/
problem232.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
//swift implementation of cpp version
//https://github.com/ChenYangyao/project-leetcode-solution/blob/master/cpp/problem232.cpp
class MyQueue {
private var queue: [Int]
private var revQueue: [Int]
private func transform(_ input: inout [Int], _ output: inout [Int]) {
while !input.isEmpty {
output.append(input.removeLast())
}
}
init() {
self.queue = [Int]()
self.revQueue = [Int]()
}
func push(_ x: Int) {
if !revQueue.isEmpty {
transform(&revQueue, &queue)
}
queue.append(x)
}
func pop() -> Int {
if !queue.isEmpty {
transform(&queue, &revQueue)
}
return revQueue.removeLast()
}
func peek() -> Int {
if !queue.isEmpty {
transform(&queue, &revQueue)
}
return revQueue.last!
}
func empty() -> Bool {
return queue.isEmpty && revQueue.isEmpty
}
}