编辑代码

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int DataType;
typedef struct {
    DataType data[MaxSize];
    int top;
} Stack;

// top:栈指针。取值范围为0~MaxSize-1
// top=-1表示空栈,top=MaxSize-1表示栈满

// 初始化栈
int InitStack(Stack *S)
{
    S->top=-1;
    return 1;
}

// 压栈Push(S,x)
int Push(Stack *S,DataType x)
{
    if(S->top==MaxSize-1)
    {
         printf("\n Stack is full!"); 
        return 0;
    }
      S->top++;
      S->data[S->top]=x;
      return 1; 
}

// 判断栈空
int EmptyStack(Stack *S)
{
    return (S->top==-1?1:0);
}

// 出栈
int Pop(Stack *S)
{
    if(EmptyStack(S))
    {
        printf("\n 是空栈");
        exit(1);
    }
  //  x=S->data[S->top]
    S->top--;
    return 1;
}

// 取栈顶元素
DataType GetTop(Stack *S)
{
    DataType x;
    if(EmptyStack(S))
    {
        printf("\n 是空栈");
        exit(1);
    }
    x=S->data[S->top];
    return x;
}

int main () {
    Stack L;
    InitStack(&L);
    Push(&L, 10);
    Push(&L, 20);
    Push(&L, 30);
    printf("栈顶元素:%d\n", GetTop(&L));
    Pop(&L);
    printf("栈顶元素:%d\n", GetTop(&L));
    return 0;
}