用两个栈模拟队列

第一个栈负责进队,第二个负责出队

用两个栈模拟队列
#include<stdio.h>
#define maxsize 10
typedef struct s {
	int data[maxsize];
	int top;
}SqStack;
int InitStack(SqStack& S1) {
	S1.top = -1;
	return 1;
}
int push(SqStack& S, int x) {	
	S.data[++S.top] = x;
	return 1;
}
int pop(SqStack& S, int& x) {
	
	x = S.data[S.top--];
	return 1;
}
int isEmpty(SqStack S) {
	if (S.top == -1) {
		return 1;
	}
	else
	{
		return 0;
	}
}
int isOverFlow(SqStack S) {
	if (S.top == maxsize - 1) {
		return 1;
	}
	else
	{
		return 0;
	}
}
int EnQueue(SqStack& S1, SqStack& S2,int x) {
	if (isOverFlow(S1)&&!isEmpty(S2)) {
		printf("栈满");
		return 0;
	}
	int e;
	if (isOverFlow(S1) && isEmpty(S2)) {
		while (!isEmpty(S1)) {
			pop(S1, e);
			push(S2,e);
		}
		push(S1, x);
		return 1;
	}
	if (!isOverFlow(S1)) {
		push(S1, x);
	}
}
void DeQueue(SqStack& S1, SqStack& S2, int &x) {
	int e;
	if (!isEmpty(S2)) {
		pop(S2, x);
	}else if (!isEmpty(S1) && isEmpty(S2)) {
		while (!isEmpty(S1)) {
			pop(S1,e);
			push(S2,e);
		}
		pop(S2, x);
	}
	else if(isEmpty(S1) && isEmpty(S2)) {
		printf("队空");
	}
	
}
int EisEmpty(SqStack S1,SqStack S2) {
	if (isEmpty(S1) && isEmpty(S2)) {
		return 1;
	}
	else {
		return 0;
	}
}
int main() {
	SqStack S1;
	SqStack S2;
	InitStack(S1);
	InitStack(S2);
	int e;
	EnQueue(S1, S2, 8);
	EnQueue(S1, S2, 5);
	EnQueue(S1, S2, 7);
	DeQueue(S1, S2, e);
	printf("%d", e);
	DeQueue(S1, S2, e);
	printf("%d", e);
	DeQueue(S1, S2, e);	
	printf("%d ", e);
	printf("%d", EisEmpty(S1, S2));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值