队列和栈

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的元素再依次入队q1
		int 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.一个数组实现三个栈:思路和上面的相似, 一可以用交叉索引,二可以从数组的首中尾分别作为三个栈的栈底。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值