两个栈实现队列;两个队列实现栈

来源:互联网 发布:网络配置路由器 编辑:程序博客网 时间:2024/05/13 14:24

1、两个栈实现队列

思路:s1是入栈的,s2是出栈的。

  入队列时:直接压入s1即可

  出队列时:如果s2不为空,把s2中的栈顶元素直接弹出;否则,把s1的所有元素全部弹出压入s2中,再弹出s2的栈顶元素



<span style="font-size:18px;">//两个栈实现一个队列,完成入栈和出栈功能#include <iostream>#include <stack>using namespace std;class Queue{stack<int>s1;stack<int>s2;public:Queue(){}~Queue(){}void push(int data);void pop();};void Queue::push(int data){s1.push(data);}void Queue::pop(){if(s2.empty())//s2为空栈,把s1全部倒入s2中{if(s1.empty())//s1也为空栈,退出{cout<<"empty"<<endl;return;}while(!s1.empty())//全部倒入{s2.push(s1.top());s1.pop();}}cout<<s2.top()<<endl;s2.pop();}void main(){Queue q;q.push(1);q.push(2);q.push(3);q.push(4);q.pop();q.pop();q.pop();q.push(5);q.push(6);q.pop();q.pop();q.pop();q.pop();system("pause");}</span>


2、两个队列实现栈

思路:q1是专职进出栈的,q2只是个中转站

  入栈时:直接入队列q1即可

  出栈时:把q1的除最后一个元素外全部转移到队q2中,然后把刚才剩下q1中的那个元素出队列。之后把q2中的全部元素转移回q1中

图示:

改进:两个队列的功能不确定,即既可以作为进出栈,又可以作为中转站

定义两个指针:pushtmp:所指专门进栈的队列; tmp:指向临时作为中转站的另一个栈。

  入栈时:直接入pushtmp所指队列即可

  出栈时:把pushtmp的除最后一个元素外全部转移到队列tmp中,然后把刚才剩下q1中的那个元素出队列。转移到另外一个队列后不用返回了,这样减少了转移的次数。

#include<iostream>#include<queue>using namespace std;//两个队列实现栈,完成入栈、出栈功能class Stack{queue<int>q1;queue<int>q2;int inq;//指示作为入栈、出栈的队列public:Stack(){inq=0;}~Stack(){}void push(int data);void pop();int top();};void Stack::push(int data){if(inq==0)q1.push(data);elseq2.push(data);}void Stack::pop(){if(inq==0){int n=q1.size();if(n==0)return;for(int i=0;i<n-1;i++){q2.push(q1.front());q1.pop();}cout<<q1.front()<<endl;q1.pop();inq=1;}else{int n=q2.size();if(n==0)return;for(int i=0;i<n-1;i++){q1.push(q2.front());q2.pop();}cout<<q2.front()<<endl;q2.pop();inq=0;}}void main(){Stack s;s.push(1);s.push(2);s.push(3);s.push(4);s.pop();s.pop();s.pop();s.push(5);s.pop();s.pop();s.pop();s.pop();system("pause");}



0 0
原创粉丝点击