您的位置:首页 > 其它

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

2016-02-24 19:09 330 查看
#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)++];
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: