算法导论 用两个队列实现一个栈 10.1-7

问题:用两个队列实现一个栈

思路:队列是先进先出,栈是后进先出。将Q.tail当成S.top,则出栈和队列的删除相同。入栈,要通过一个空的队列L1和另一个存有之前值的队列L2,设值x要存入栈中,则先将x存入空的队列L1中,再依次将L2的值取出加入到L1中。

代码:

#include<iostream>

using namespace std;

//先实现队列及其基本操作

//队列结构
struct queue
{
	int head;
	int tail;
	int length;
	int *value;
	queue(int size):head(0),tail(0),length(size){value=new int[size];};
	//~queue(){delete[] value;};
};

//检查队列是否为空
int QueueEmpty(queue q)
{
	if(q.head==q.tail)
		return 1;
	return 0;
}

//边界转换
int change(int index,int size)
{
	int t;
	if(index==size-1)
		t=1;
	else
		t=index+1;
	return t;
}

//检查队列是否已满
int QueueFull(queue q)
{
	int t=change(q.tail,q.length);
	if(t==q.head)
		return 1;
	return 0;
}

//入队:添加到队尾
int Enqueue(queue & q,int x)
{
	if(QueueFull(q))
	{
		cout<<"overflow"<<endl;
		return -1;
	}
	q.value[q.tail]=x;
	q.tail=change(q.tail,q.length);
}

//出队:从队首出队
int Dequeue(queue & q)
{
	if(QueueEmpty(q))
	{
		cout<<"underflow"<<endl;
		return NULL;
	}
	int x=q.value[q.head];//返回的应该是删除的值,否则后面会出错
	q.head=change(q.head,q.length);
	return x;
}

//打印队列
void QPrint(queue q)
{
	if(q.tail>q.head)
	{
		for(int i=q.head;i<q.tail;i++)
			cout<<q.value[i]<<" ";
		cout<<endl;
	}
	if(q.tail<q.head)
	{
		for(int j=q.head;j<q.length;j++)
			cout<<q.value[j]<<" ";
		for(int k=0;k<q.tail;k++)
			cout<<q.value[k]<<" ";
		cout<<endl;
	}
}

//实现出栈
int Pop(queue & q1, queue & q2)
{
	if(!QueueEmpty(q1))
		return Dequeue(q1);
	if(!QueueEmpty(q2))
		return Dequeue(q2);
	cout<<"underflow"<<endl;
	return NULL;
}

//实现入栈
int Push(queue & q1,queue & q2, int x)
{
	if(QueueEmpty(q1))
	{
		if(QueueFull(q2))
		{
			cout<<"overflow"<<endl;
			return -1;
		}
		Enqueue(q1,x);

		while(!QueueEmpty(q2))
			Enqueue(q1,Dequeue(q2));
		QPrint(q1);
		QPrint(q2);
	}
	else
	{
		if(QueueFull(q1))
		{
			cout<<"overflow"<<endl;
			return -1;
		}
		Enqueue(q2,x);
		while(!QueueEmpty(q1))
			Enqueue(q2,Dequeue(q1));
		QPrint(q1);
		QPrint(q2);
	}
}

//打印栈
void SPrint(queue q1,queue q2)
{
	if(!QueueEmpty(q1))
		 QPrint(q1);
	else
		 QPrint(q2);
}


int main()
{
	queue a(10);
	queue b(10);
	for(int i=1;i<6;i++)	
		Push(a,b,2*i);
	SPrint(a,b);
	for(int j=1;j<7;j++)
	{
		Pop(a,b);
		SPrint(a,b);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值