用一个数组表示两个栈,只要数组有空间,往栈中添加元素就能成功

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 6
/*
   用一个数组表示两个栈,只要数组有空间,往栈中添加元素就能成功。 
*/
typedef int ElementType;
typedef struct{
	ElementType Data[MAXSIZE];
	int top1;
	int top2;
}Stack;
// 创建一个空的栈 
Stack* CreateStack( );
//压入栈 
void Push(Stack* sp,ElementType item,int tag);
//取出最上端的元素 
ElementType Pop(Stack* sp,int tag);

int main(){
	Stack* sp=CreateStack(10);
	ElementType item;
	Push(sp,1,1);
	Push(sp,2,1);
	Push(sp,1,2);
	Push(sp,2,2);
	item=Pop(sp,1);
	printf("1pop:%d\n",item);
	item=Pop(sp,1);
	printf("1pop:%d\n",item);
	item=Pop(sp,2);
	printf("2pop:%d\n",item);
	item=Pop(sp,2);
	printf("2pop:%d\n",item);
	return 0;
} 
Stack* CreateStack()
{
	Stack* s=(Stack*)malloc(sizeof(Stack));
	s->top1=-1;
	s->top2=MAXSIZE;
	return s;
} 
void Push(Stack* sp,ElementType item,int tag)
{
	//判断是否已满
	if(sp->top2-sp->top1==1){
		printf("栈已满\n");
		return;
	} else{
		if(tag==1)
		{
			sp->Data[++(sp->top1)]=item;
		}else
		{
			sp->Data[--(sp->top2)]=item;
		} 
	}
}
 
ElementType Pop(Stack* sp,int tag)
{
	ElementType data;
	if(tag==1)
	{
		if(sp->top1==-1)
		{
			printf("栈1已空\n");
			return NULL;
		}else
		{
			data=sp->Data[(sp->top1)--];
		}
	}else
	{
		if(sp->top2==(MAXSIZE+1))
		{
			printf("栈2已空\n");
			return NULL;
		}else
		{
			data=sp->Data[(sp->top2)++];
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值