Two stacks implement one queue and two stacks implement queues.
Use two stacks to implement a queue function.
Solutions
Assume that both stacks A and B are empty.
Stack A providespush()
Function, stack B providespop()
Function.
- Inbound queue: Inbound stack.
- Outbound queue:
- If Stack B is not empty, the B element is displayed directly.
- If Stack B is empty, the elements of stack A are popped up and pushed to stack B. Then, the elements of stack B are popped up.
Implementation Code
#include <iostream>#include <stack>using namespace std;template<class T>class MyQueue{public: void push(const T& t) { s1.push(t); } void pop() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } s2.pop(); } T& top() { if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } bool empty() const { return s1.empty() && s2.empty(); }private: stack<T> s1; stack<T> s2;};int main(){ MyQueue<int> myque; for (int i = 0; i < 10; i++) { myque.push(i); } while (!myque.empty()) { cout<<myque.top()<<" "; myque.pop(); }}
Note:pop()
Andtop()
Not addedif (!s2.empty())
In my opinion, this should be determined by the user.MyQueue
Whether the object is null can reduce unnecessary judgment to improve program efficiency.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.