Created
November 10, 2015 22:51
-
-
Save beinan/d312d8915f98d68bb66c to your computer and use it in GitHub Desktop.
Implement a stack by a single queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <queue> | |
class Stack { | |
queue<int> _q; | |
public: | |
// Push element x onto stack. | |
void push(int x) { | |
_q.push(x); | |
} | |
// Removes the element on top of the stack. | |
void pop() { | |
for(int i = 0; i < _q.size() - 1; i++){ | |
int temp = _q.front(); | |
_q.pop(); | |
_q.push(temp); | |
} | |
_q.pop(); | |
} | |
// Get the top element. | |
int top() { | |
for(int i = 0; i < _q.size() -1; i++){ | |
int temp = _q.front(); | |
_q.pop(); | |
_q.push(temp); | |
} | |
int top = _q.front(); | |
_q.pop(); | |
_q.push(top); | |
return top; | |
} | |
// Return whether the stack is empty. | |
bool empty() { | |
return _q.empty(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment