#include <stdio.h>
#include <stdlib.h>
#define ERROR 1e8
#include <string.h>
typedef int ElementType;
typedef enum { push, pop, end } Operation;
//typedef enum { false, true } bool;这个是C语言内置的,不用去声明
typedef int Position;
struct SNode {
ElementType *Data;
Position Top1, Top2;
int MaxSize;
};
typedef struct SNode *Stack;
Stack CreateStack( int MaxSize );
bool Push( Stack S, ElementType X, int Tag );
ElementType Pop( Stack S, int Tag );
Operation GetOp(); /* details omitted */
void PrintStack( Stack S, int Tag ); /* details omitted */
int main()
{
int N, Tag, X;
Stack S;
int done = 0;
scanf("%d", &N);
S = CreateStack(N);
while ( !done ) { //非done,则成立。
switch( GetOp() ) {
case push:
scanf("%d %d", &Tag, &X);
if (!Push(S, X, Tag)) printf("Stack %d is Full!\n", Tag);
break;
case pop:
scanf("%d", &Tag);
X = Pop(S, Tag);
if ( X==ERROR ) printf("Stack %d is Empty!\n", Tag);
break;
case end:
PrintStack(S, 1);
PrintStack(S, 2);
done = 1;
break;
}
}
return 0;
}
Stack CreateStack( int MaxSize )
{
Stack S;
S=(Stack)malloc(sizeof(struct SNode));//为struct SNode分配内存 (地址)malloc(结构体)
S->MaxSize=MaxSize; //初始化struct SNode{}里的元素
S->Data=( ElementType*)malloc(sizeof(ElementType)*MaxSize); //struct SNode{}里的元素分配内存
S->Top1=-1;//初始化struct SNode{}里的元素
S->Top2=MaxSize;//初始化struct SNode{}里的元素
return S;
}
bool Push( Stack S, ElementType X, int Tag )
{
if(S == NULL) //如果分配不成功
return false;
if((S->Top1+1)==S->Top2)
{
printf("Stack Full\n");
return false;
}
else if(Tag==1)
{
S->Data[++(S->Top1)]=X;
return true;
}
else if(Tag==2)
{
S->Data[--(S->Top2)]=X;
return true;
}
else
return false;
}
ElementType Pop( Stack S, int Tag )
{
if(S == NULL)
return ERROR;
if(Tag==1)
{
if(S->Top1==-1)
{
printf("Stack %d Empty\n", Tag);
return ERROR;
}
else
return S->Data[(S->Top1)--];
}
else if(Tag==2)
{
if(S->Top2==S->MaxSize)
{
printf("Stack %d Empty\n", Tag);
return ERROR;
}
else
return S->Data[(S->Top2)++];
}
else
return ERROR;
}
//PrintStack()函数
void PrintStack( Stack S, int Tag )
{
if(Tag==1)
{
printf("Pop from Stack 1:");
for(int i=S->Top1;i>-1;i--)
{
printf("%3d",S->Data[i]);
}
printf("\n");
}
else
{
printf("Pop from Stack 2:");
for(int j=S->Top2;j<S->MaxSize;j++)
{
printf("%3d",S->Data[j]);
}
printf("\n");
}
}
Operation GetOp() //Operation()因为是typedef enum { push, pop, end } Operation
{ //所以要返回其中任意一种
char a[5];
scanf("%s",a);/*字符串的定义与输入*/
if(strcmp(a,"Push")==0) return push;/*strcmp()函数的应用*/
if(strcmp(a,"Pop")==0) return pop;
if(strcmp(a,"End")==0) return end;
}
/*1、在写这一个代码时,由于自己喜欢复制的习惯导致if(Tag==1)else if(Tag==1)以及
S->Top1=-1;S->Top2=MaxSize;以至于代码一直出现乱码以及Pop2时一直没有反应*/
/*2、在PTA里编译应注意严格按照他给的格式进行排局,否则编译不通过*/
转载于:https://www.cnblogs.com/fllowcool/p/5957993.html