Skip to content

Commit 2ea98e4

Browse files
Create stack_using_queue.cpp
1 parent 935fffe commit 2ea98e4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

stack_using_queue.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class MyStack {
2+
public:
3+
/** Initialize your data structure here. */
4+
queue<int> mainQueue, tempQueue;
5+
MyStack() {
6+
}
7+
8+
/** Push element x onto stack. */
9+
void push(int x) {
10+
while(!mainQueue.empty())
11+
{
12+
tempQueue.push(mainQueue.front());
13+
mainQueue.pop();
14+
}
15+
mainQueue.push(x);
16+
while(!tempQueue.empty())
17+
{
18+
mainQueue.push(tempQueue.front());
19+
tempQueue.pop();
20+
}
21+
}
22+
23+
/** Removes the element on top of the stack and returns that element. */
24+
int pop() {
25+
int val = mainQueue.front();
26+
mainQueue.pop();
27+
return val;
28+
}
29+
30+
/** Get the top element. */
31+
int top() {
32+
return mainQueue.front();
33+
}
34+
35+
/** Returns whether the stack is empty. */
36+
bool empty() {
37+
return mainQueue.empty();
38+
}
39+
};
40+
41+
42+
/**
43+
* Your MyStack object will be instantiated and called as such:
44+
* MyStack* obj = new MyStack();
45+
* obj->push(x);
46+
* int param_2 = obj->pop();
47+
* int param_3 = obj->top();
48+
* bool param_4 = obj->empty();
49+
*/

0 commit comments

Comments
 (0)