编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MaxSize 10

typedef struct {
  int data[MaxSize];
  int top;
} Stack;

bool InitStack(Stack* S) {
  S->top = -1;
  return true;
}

bool Push(Stack* S, int e) {
  if (S->top == MaxSize - 1) return false;
  S->data[++(S->top)] = e;
  return true;
}

bool Pop(Stack* S, int* e) {
  if (S->top == -1) return false;
  *e = S->data[(S->top)--];
  return true;
}

bool GetTop(Stack* S, int* e) { //注意,这里需要传递栈的指针,不然调用不了。
  if (S->top == -1) return false;
  *e = S->data[(S->top)];
  return true;
}

int main() {
  Stack L;
  InitStack(&L);
  for (int i = 0; i < 5; i++) Push(&L, i);
  int e;
  GetTop(&L, &e);
  printf("Top element: %d\n", e);
  return 0;
}