Skip to content

Instantly share code, notes, and snippets.

@beinan
Created November 10, 2015 22:51
Show Gist options
  • Save beinan/d312d8915f98d68bb66c to your computer and use it in GitHub Desktop.
Save beinan/d312d8915f98d68bb66c to your computer and use it in GitHub Desktop.
Implement a stack by a single queue
#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