共享栈=栈1+栈2
栈1的栈底为共享栈的首,栈2的栈底为共享栈的尾
共享栈满:S->top1+1==S->top2
//Author:张佳琪
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 80
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType data[MAXSIZE];
int top1;
int top2;
}Stack;
Status init(Stack *S)
{
S->top1=-1;
S->top2=MAXSIZE;
return OK;
}
Status push(Stack *S,ElemType e,int stacknumber)
{
if(S->top1+1==S->top2)
return ERROR;
if(stacknumber==1)
{
S->data[++S->top1]=e;
}
else if(stacknumber==2)
{
S->data[--S->top2]=e;
}
return OK;
}
Status pop(Stack *S,ElemType *e,int stacknumber)
{
if(stacknumber==1)
{
if(S->top1==-1)
return ERROR;
*e=S->data[S->top1--];
}
else if(stacknumber==2)
{
if(S->top2==MAXSIZE)
return ERROR;
*e=S->data[S->top2++];
}
return OK;
}
Status show(Stack *S,int stacknumber)
{
int i;
if(stacknumber==1)
{
if(S->top1==-1)
return ERROR;
printf("栈1:");
for(i=0;i<=S->top1;i++)
printf("%d ",S->data[i]);
printf("\n=================\n");
}
else if(stacknumber==2)
{
if(S->top2==MAXSIZE)
return ERROR;
printf("栈2:");
for(i=MAXSIZE-1;i>=S->top2;i--)
printf("%d ",S->data[i]);
printf("\n=================\n");
}
return OK;
}
int main()
{
Stack S;
ElemType x;
int i;
while(1)
{
printf("=====menu=====\n");
printf("1.初始化\n");
printf("2.入栈\n");
printf("3.出栈\n");
printf("4.输出\n");
printf("输入1-4:");
scanf("%d",&i);
switch(i)
{
case 1:
{
if(init(&S))
printf("完成!\n");
else
printf("失败!\n");
break;
}
case 2:
{
printf("栈1还是栈2:");
scanf("%d",&i);
printf("输入数据:");
scanf("%d",&x);
push(&S,x,i);
break;
}
case 3:
{
printf("栈1还是栈2:");
scanf("%d",&i);
pop(&S,&x,i);
printf("%d\n",x);
break;
}
case 4:
{
printf("栈1还是栈2:");
scanf("%d",&i);
show(&S,i);
break;
}
}
}
}