队列和栈

来源:互联网 发布:淘宝有好看的衣服牌子 编辑:程序博客网 时间:2024/04/25 19:17

http://www.cnblogs.com/Jax/archive/2009/12/28/1628552.html

1.用两个队列实现栈的压入和弹出(这里弹出时会返回弹出的元素)

#include<iostream>#include<stack>#include<queue>#include<deque>using namespace std;queue<int> q1,q2;// 队列实现栈void push(int x){q1.push(x);}int pop(){while(q1.size()>1){//当q1中只有一个元素时,即最后入队的值int temp=q1.front();q1.pop();q2.push(temp);}int result=q1.front();q1.pop();while(q2.size()!=0){//将q2的元素再依次入队q1int s=q2.front();q2.pop();q1.push(s);}return result;}

2.递归地反转一个栈

详解

void reverse(stack<int> &s){if(s.empty())return;int top1=s.top();s.pop();if(s.empty()){s.push(top1);return;}reverse(s);int top2=s.top();//将栈底元素拿出s.pop();reverse(s);s.push(top1);//维护原结构reverse(s);s.push(top2);}
3.递归排序栈,从小到大
void sort(stack<int> &s){if(s.empty())return;int top1=s.top();s.pop();if(s.empty()){s.push(top1);return;}sort(s);int min=s.top();//找到剩下栈中元素的最小者s.pop();if(top1>min){//通过最小者和栈顶元素的比较。选择不同的方案使得栈中元素排序s.push(top1);sort(s);s.push(min);}else{s.push(min);s.push(top1);}}

4.一个数组实现两个栈

方法1:数组的首尾分别作为stack1,stack2的栈底,分别向左右增长

class TwoStack{//首尾递增public:TwoStack(int n){m=n;num=new int[n];top1=-1;top2=n;}~TwoStack(){delete num;}void push(int type, int i){if(type==0){if(top1+1==top2){ //防止下标空加,造成错误cout<<"stack1 is full."<<endl;return;}++top1;num[top1]=i;}else{if(top2-1==top1){cout<<"stack2 is full."<<endl;return;}--top2;num[top2]=i;}}int pop(int type){if(type==0){if(top1==-1){cout<<"stack1 is empty"<<endl;return 0;}return num[top1];--top1;}else{if(top2==m){cout<<"stack2 is empty"<<endl;return 0;}return num[top2];++top2;}}public:int* num;unsigned int m;int top1;int top2;};

方法2:交叉索引,两个栈子数组中的下标分别是0,2,4,6......;1,3,5,7.....

class TwoStack1{//交叉索引public:TwoStack1(int n){m=n;num=new int[n];top1=-2;top2=-1;}~TwoStack1(){delete num;}void push(int type, int i){if(type==0){if(top1+2>=m){cout<<"stack1 is full."<<endl;return;}top1+=2;num[top1]=i;}else{if(top2+2>=m){cout<<"stack2 is full."<<endl;return;}top2+=2;num[top2]=i;}}int pop(int type){if(type==0){if(top1<0){cout<<"stack1 is empty"<<endl;return 0;}return num[top1];top1-=2;}else{if(top2<0){cout<<"stack2 is empty"<<endl;return 0;}return num[top2];top2-=2;}}public:int* num;unsigned int m;int top1;int top2;};

5.一个数组实现三个栈:思路和上面的相似,一可以用交叉索引,二可以从数组的首中尾分别作为三个栈的栈底。



0 0
原创粉丝点击