#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)++];
}
}
}
用一个数组表示两个栈,只要数组有空间,往栈中添加元素就能成功
最新推荐文章于 2021-03-31 16:53:06 发布