用两个栈模拟一个队列的运算

原题:用两个栈模拟一个队列运算的基本思想是用一个栈作为输入,另一个栈作为输出。进队列时,将数据进入到作为输入的栈中。输出时,如果作为输出的栈已空,则从输入栈将已输入到栈中的所有数据输入到输出栈中,然后由输出栈输出数据;如果作为输出的栈不空,则就从输出栈输出数据。显然,只有在输入、输出栈均为空时队列才空。

程序如下:

#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#define INIT_SIZE 100//存储空间初始分配量
#define INCREMENT 10//存储空间分配增量
#define ElemType char

typedef struct 
{
	ElemType *base;//在栈构造之前和销毁之后,base值为NULL
	ElemType *top;//栈顶指针
	int stacksize;//当前已分配的存储空间,以元素为单位
}SqStack;

typedef struct 
{
	SqStack S1;
	SqStack S2;
}DSQueue;

int InitStack(SqStack &S)
{//构造一个空栈
	S.base=new ElemType[INIT_SIZE];
	if(S.base == NULL)
	{//溢出
		cout<<"存储空间分配失败!"<<endl;return -1;
	}
	S.top=S.base;//S.top=S.base表示为空栈
	S.stacksize=INIT_SIZE;//为栈容量赋初值
	return 1;
}

int Pop(SqStack &S,ElemType &e)
{//如栈非空,则删除栈顶元素
	if(S.base == S.top)
	{//栈空条件下执行
		cout<<"当前栈已空!"<<endl;return -1;
	}
	e=*--S.top;//可利用e返回被删除的栈顶元素值
	return 1;
}

int Push(SqStack &S,ElemType e)
{//入栈操作
	if(S.top - S.base >= S.stacksize)
	{//栈满条件下,扩大栈的容量
		ElemType *tem,*p;
		int i=0;
		tem=new ElemType[S.stacksize + INCREMENT];//新栈的空间
		if(tem == NULL)
		{//溢出
			cout<<"追加存储空间失败!"<<endl<<endl;return -1;
		}
		p=S.base;
		while(p != S.top)//复制数据元素值到tem所指空间中
			tem[i++]=*p++;
		delete[] S.base;//释放S.base所指空间
		S.base=tem;//S.base指向新空间
		S.top=S.base + S.stacksize;//设置新栈顶
		S.stacksize+=INCREMENT;//设置新栈容量
	}
	*S.top++=e;
	return 1;
}

int StackEmpty(SqStack S)
{
	if(S.top == S.base)
	{
		return 1;
	}
	else
	{
		return -1;
	}
}

void InitQueue(DSQueue &Q)
{//初始化队列
	InitStack(Q.S1);
	InitStack(Q.S2);
}

int EnQueue(DSQueue &Q,ElemType e)
{//入队列操作
	Push(Q.S1,e);
	return 1;
}

int QueueEmpty(DSQueue Q)
{//判断队列是否为空
	if(StackEmpty(Q.S1) == 1 && StackEmpty(Q.S2) == 1)
	{
		cout<<"当前队列为空!"<<endl<<endl;return 1;
	}
	return -1;
}

int DeQueue(DSQueue &Q)
{//删除队列Q的队头元素
	ElemType e;
	if(QueueEmpty(Q) == 1)
	{
		cout<<"当前队列已空!"<<endl<<endl;return -1;
	}
	if(StackEmpty(Q.S2) == 1)
	{
		while(StackEmpty(Q.S1) == -1)
		{
			Pop(Q.S1,e);
			Push(Q.S2,e);
		}
	}
	Pop(Q.S2,e);
	cout<<"元素 "<<e<<" 出队列!"<<endl;
	return 1;
}

int DisplayQueue(DSQueue Q)
{//从队尾到队头输出队列元素的值
	int k,len1=Q.S1.top - Q.S1.base;
	int len2=Q.S2.top - Q.S2.base;
	cout<<"从队尾到队头输出当前队列的数据为:"<<endl;
	if(len1>0)
	{
		for(k=len1-1;k>=0;k--)
		{
			cout<<Q.S1.base[k]<< "  ";
		}
	}
	if(len2>0)
	{
		for(k=0;k<len2-1;k++)
		{
			cout<<Q.S2.base[k]<< "  ";
		}	
		cout<<Q.S2.base[k]<<endl<<endl;
	}
	cout<<endl;
	return 1;
}

int main()
{
	char e;
	DSQueue Q;
	InitQueue(Q);
	srand((unsigned)time(NULL));
	for(int k=0;k<20;k++)
	{
		e=rand()%26+'a';
		EnQueue(Q,e);
	}
	DisplayQueue(Q);
	for(k=0;k<5;k++)
	{
		DeQueue(Q);
	}
	for(k=0;k<5;k++)
	{
		e=(char)(rand()%26+'a');
		cout<<"元素 "<<e<<" 入队列!"<<endl;
		EnQueue(Q,e);
	}
	DisplayQueue(Q);
	return 1;
}

你可能感兴趣的:(算法,模拟,栈,队列)