Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create implementing a stack using two queues.cpp #1420

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions implementing a stack using two queues.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <iostream>
#include <queue>

using namespace std;

class StackUsingQueues {
public:
void push(int x) {
q1.push(x);
}

int pop() {
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
int popped = q1.front();
q1.pop();
swap(q1, q2);
return popped;
}

int top() {
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
int topElement = q1.front();
q2.push(topElement);
swap(q1, q2);
return topElement;
}

bool empty() {
return q1.empty();
}

private:
queue<int> q1, q2;
};

int main() {
StackUsingQueues stack;

stack.push(1);
stack.push(2);
stack.push(3);

cout << "Top element: " << stack.top() << endl;
cout << "Popped element: " << stack.pop() << endl;

cout << "Top element: " << stack.top() << endl;
cout << "Is stack empty? " << (stack.empty() ? "Yes" : "No") << endl;

return 0;
}