Skip to content

Commit 0ecc28b

Browse files
authored
Create queue_using_stack.cpp
1 parent 5f41a9a commit 0ecc28b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
class MyQueue {
3+
public:
4+
stack<int> temp, ans;
5+
/** Initialize your data structure here. */
6+
MyQueue() {
7+
8+
}
9+
10+
/** Push element x to the back of queue. */
11+
void push(int x) {
12+
temp.push(x);
13+
}
14+
15+
/** Removes the element from in front of queue and returns that element. */
16+
int pop() {
17+
// shift input to output
18+
if (ans.empty())
19+
while (temp.size())
20+
ans.push(temp.top()), temp.pop();
21+
22+
int x = ans.top();
23+
ans.pop();
24+
return x;
25+
}
26+
27+
/** Get the front element. */
28+
int peek() {
29+
// shift input to output
30+
if (ans.empty())
31+
while (temp.size())
32+
ans.push(temp.top()), temp.pop();
33+
return ans.top();
34+
}
35+
36+
/** Returns whether the queue is empty. */
37+
bool empty() {
38+
return temp.empty() && ans.empty();
39+
}
40+
41+
};

0 commit comments

Comments
 (0)