数据结构习题——共享栈的入栈Push和出栈Pop/双栈模拟队列

前言

关于共享栈

正文

题目一

共享栈的入栈和出栈操作
共享栈特点

  • 栈满top1-top0=0
  • 栈空top0=-1,top1=maxsize;
  • 左边入栈出栈和右边入栈出栈top移动相反(具体见代码)

代码

#define maxsize 100
typedef struct{
	int stack[maxsize];
	int top[2];
}stk;
stk s;
//入栈操作
int push(int i,int x){
	if(i<0||i>1){
		printf("栈号不对")exit(0); 
	}
	if(s.top[1]-s.top[0]==1){
		printf("栈满");
		return 0; 
	}
	switch(i){
		case 0: s.stack[++s.top[0]]==x;return 1;break;
		case 1: s.stack[--s.top[1]]==x;return 1;
	}
} 
//出栈操作
int pop(int i){
	if(i<0||i>1){
		printf("栈号不对")exit(0); 
	}
	switch(i){
		case 0:
			if(s.top[0]==-1){
				printf("栈空");
				return -1;
			}
			else
				return s.stack[s.top[0]--];
	    case 1:
			if(s.top[1]==maxsize){
				printf("栈空");
				return -1;
			}
			else
				return s.stack[s.top[1]++];
	}
}

题目二

利用两个栈s1,s2来模拟一个队列
已知栈的四个基本操作,push,pop,StackEmpty,StackOverflow.
总结:

  • 对s2的出栈用作出队,若s2为空,则先将s1中的所有元素送入s2
  • 对s1的入栈操作用作入队,若s1满,先必须保证s2为空,才能将s1中的元素全部插入s2中
/*入队操作*/
int EnQueue(Stack &s1,Stack &s2,int x){
	if(!StackOverflow(s1)){
		push(s1,x);
		return 1;
	}
	if(StackOverflow(s1)&&!StackEmpty(s2)){
		printf("队列满"); 
		return 0;
	}
	if(StackOverflow(s1)&&StackEmpty(s2)){
		while(!StackEmpty(s1)){
			pop(s1,x);
			push(s2,x);
		}
	}
	push(s1,x);
	return 1;
} 
/*出队操作*/
void DeQueue(Stack &s1,Stack &s2,int &x){
	if(!StackEmpty(s2)){
		pop(s2,x);
	}
	else if(StackEmpty(s1))
        printf("队列为空");
	else{
		while(!StackEmpty(s1)){
			pop(s1,x);
			push(s2,x);
		}
		pop(s2,x);
	} 
}
/*判断队空*/
int QueueEmpty(Stack s1,Stack s2){
	if(StackEmpty(s1)&&StackEmpty(s2))
       return 1;
    else
       return 0;
} 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值