/
232_implementQueueUsingStacks.cpp
55 lines (48 loc) · 1.37 KB
/
232_implementQueueUsingStacks.cpp
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
// Sourse : https://leetcode.com/problems/implement-queue-using-stacks/
// Difficulty : Easy
/***********************************************************************
*
* 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.
*
**********************************************************************/
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
stackin.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if (stackout.empty()) {
while (!stackin.empty()) {
stackout.push(stackin.top());
stackin.pop();
}
}
if (!stackout.empty()) {
stackout.pop();
}
}
// Get the front element.
int peek(void) {
if (stackout.empty()) {
while (!stackin.empty()) {
stackout.push(stackin.top());
stackin.pop();
}
}
return stackout.top();
}
// Return whether the queue is empty.
bool empty(void) {
return stackin.empty() && stackout.empty();
}
private:
stack<int> stackin;
stack<int> stackout;
};