详解C语言之堆栈

  #include

  #include

  typedef int DataType;

  typedef struct snode

  {

  DataType data;

  struct snode *next;

  }LSNode;

  //初始化

  void StackInit(LSNode **top)

  {

  *top = (LSNode *)malloc(sizeof(LSNode));

  (*top)->next = NULL;

  }

  //判断堆栈是否非空

  int StackIsEmpty(LSNode *top)

  {

  if (top->next == NULL)

  return 0;

  else

  return 1;

  }

  //入栈

  void StackPush(LSNode *top, DataType x)

  {

  LSNode *p;

  p = (LSNode *)malloc(sizeof(LSNode));

  p->data = x;

  p->next = top->next;

  top->next = p;

  }

  //出栈

  int StackPop(LSNode *top, DataType *x)

  {

  LSNode *p = top->next;

  if (p == NULL)

  {

  printf("堆栈已空,删除错误!!!

  ");

  return 0;

  }

  top->next = p->next;

  *x = p->data;

  free(p);

  return 1;

  }

  //获取栈顶元素

  int StackGetTop(LSNode *top, DataType *x)

  {

  LSNode *p = top->next;

  if (p == NULL)

  {

  printf("堆栈已空,取出错误!!!

  ");

  return 0;

  }

  *x = p->data;

  return 1;

  }

  //释放内存空间

  void StackDestroy(LSNode **top)

  {

  LSNode *p, *q;

  p = *top;

  while (p != NULL)

  {

  q = p;

  p = p->next;

  free(q);

  }

  *top = NULL;

  }

  int main()

  {

  int i, x;

  LSNode *top;

  StackInit(&top);

  for (i = 0; i < 10; i++)

  StackPush(top, i + 1);

  StackGetTop(top, &x);

  printf("当前栈顶元素为%d

  ", x);

  printf("依次出栈:");

  while (StackIsEmpty(top))

  {

  StackPop(top, &x);

  printf("%4d", x);

  }

  StackDestroy(&top);

  system("pause");

  return 0;

  }