栈的操作(有些小问题,帮忙看看)
#include<malloc.h> /* malloc()等 */#include<stdio.h> /* EOF(=^Z或F6),NULL */
#include<stdlib.h> /* atoi() */
#include<process.h> /* exit() */
struct StackRecord;
typedef struct StackRecord *Stack;
typedef char ElementType;
#define EmptyTOS -1
#define MinStackSize 5
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
void MakeEmpty(Stack S)
{
S->TopOfStack=EmptyTOS;
}
int IsFull(Stack S)
{ return S->TopOfStack== S->Capacity;
}
int IsEmpty(Stack S)
{ return S->TopOfStack==EmptyTOS;
}
Stack CreateStack(int MaxElements )
{
Stack S;
/* 1 */ if(MaxElements<MinStackSize)
/* 2 */ {printf("Stack size is too small");
exit(0);
}
/* 3 */ S=(Stack)malloc(sizeof(struct StackRecord ) );
/* 4 */ if(S==NULL)
/* 5 */ { printf("Out of space!!l");
exit(0);
}
/* 6 */ S->Array=(ElementType *)malloc(sizeof(ElementType)*MaxElements);
/* 7 */ if(S->Array==NULL)
/* 8 */ { printf("Out of space!!l");
exit(0);
}
/* 9 */ S->Capacity=MaxElements;
/*10*/ MakeEmpty(S);
/*11*/ return S;
}
/*void DisposeStack(Stack S)
{
if(S!=NULL)
{
free(S->Array);
free(S);
}
}
*/
void Push(ElementType X, Stack S)
{
if( IsFull(S) )
{ printf("Full stack");
exit(0); }
else
S->Array[++S->TopOfStack]=X;//将元素X放入栈中
}
ElementType Top(Stack S)
{
if(!IsEmpty(S) )
return S->Array[S->TopOfStack] ;//返回栈顶元素
/* Return value used to avoid warning */
}
void Pop(Stack S)
{
if(IsEmpty(S) )
{ printf("Empty stack");
exit(0);
}
else
S->TopOfStack-- ;
}
ElementType TopAndPop(Stack S )
{
if(!IsEmpty(S) )
return S->Array[S->TopOfStack--];
}
void main(void)
{
char c1,c2;
Stack S;
int i,MAX;
scanf("%d",&MAX);getchar();
S=CreateStack(MAX );//建立一个大小MAX的栈
for(i=1;i<=MAX;i++)
{
scanf("%c\n",&c1);//通过键盘输入为变量c1赋值
Push(c1, S);//将c1压入栈中
}
//输出栈顶元素
/*printf("栈顶元素为c2=%c\n",Top(S));
Pop(S); //栈顶元素出栈
*/for( i=0; i<=MAX; i++)
printf("%c ",TopAndPop( S ));// 输出栈序列
}