forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimplementQueueUsingStack.swift
More file actions
39 lines (33 loc) · 1018 Bytes
/
implementQueueUsingStack.swift
File metadata and controls
39 lines (33 loc) · 1018 Bytes
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
/*
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
https://leetcode.com/problems/implement-queue-using-stacks/
*/
class MyQueue {
var queue: [Int]
/** Initialize your data structure here. */
init() {
queue = [Int]()
}
/** Push element x to the back of queue. */
func push(_ x: Int) {
queue.append(x)
}
/** Removes the element from in front of queue and returns that element. */
func pop() -> Int {
guard !queue.isEmpty else { fatalError() }
return queue.removeFirst()
}
/** Get the front element. */
func peek() -> Int {
guard !queue.isEmpty else { fatalError() }
return queue.first!
}
/** Returns whether the queue is empty. */
func empty() -> Bool {
return queue.isEmpty
}
}