forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0225-implement-stack-using-queues.swift
80 lines (67 loc) · 1.39 KB
/
0225-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
/**
* Question Link: https://leetcode.com/problems/implement-stack-using-queues/
*/
class ListNode {
var val: Int
var next: ListNode?
init(_ val: Int) {
self.val = val
}
}
class Queue {
var head: ListNode?
var tail: ListNode?
var size = 0
func enqueue(_ val: Int) {
let node = ListNode(val)
if head == nil {
head = node
tail = node
} else {
tail?.next = node
tail = tail?.next
}
size += 1
}
func dequeue() -> Int {
if head == nil {
return -1
}
let val = head?.val
head = head?.next
if head == nil {
tail = nil
}
size -= 1
return val ?? -1
}
}
class MyStack {
var queue = Queue()
init() {
}
func push(_ x: Int) {
queue.enqueue(x)
}
func pop() -> Int {
for _ in 0..<queue.size - 1 {
let val = queue.dequeue()
queue.enqueue(val)
}
return queue.dequeue()
}
func top() -> Int {
queue.tail?.val ?? -1
}
func empty() -> Bool {
queue.size == 0
}
}
/**
* 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()
*/