-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path225-implement-stack-using-queues.swift
107 lines (90 loc) · 1.99 KB
/
225-implement-stack-using-queues.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class MyStack {
var queue = Queue<Int>()
var _top = 0
/** Initialize your data structure here. */
init() {
}
/** Push element x onto stack. */
func push(_ x: Int) {
_top = x
queue.enqueue(x)
}
/** Removes the element on top of the stack and returns that element. */
func pop() -> Int {
var i = queue.size - 1
while i != 0 {
i -= 1
let element = queue.front
queue.dequeue()
queue.enqueue(element)
if i == 0 {
_top = element
}
}
let result = queue.front
queue.dequeue()
return result
}
/** Get the top element. */
func top() -> Int {
_top
}
/** Returns whether the stack is empty. */
func empty() -> Bool {
queue.isEmpty
}
}
class Queue<T> {
private class Node<T> {
var val: T, next: Node<T>?
init(_ val: T) {
self.val = val
}
}
private var head: Node<T>?
private var tail: Node<T>?
init() {}
var size = 0
var front: T {
head!.val
}
var rear: T {
tail!.val
}
var isEmpty: Bool {
head == nil
}
func enqueue(_ val: T?) {
guard let val = val else { return }
let node = Node(val)
if let tail = tail {
tail.next = node
} else {
head = node
}
tail = node
size += 1
}
func dequeue() {
if head === tail {
head = nil
tail = nil
} else {
head = head?.next
}
size = max(0, size - 1)
}
deinit {
while !isEmpty {
dequeue()
}
}
}
/**
* Your MyStack object will be instantiated and called as such:
* let obj = MyStack()
* obj.push(x)
* let ret_2: Int = obj.pop()
* let ret_3: Int = obj.top()
* let ret_4: Bool = obj.empty()
*/