链栈的基本运算

链式栈的定义

  1. #include <malloc.h>
  2. typedef char ElemType;
  3. typedef struct lsnode
  4. {
  5. ElemType data; /*存储结点数据*/
  6. struct lsnode *next; /*指针域*/
  7. } LinkStack;

初始化栈

  1. void InitStack(LinkStack *&ls) /*ls为引用型参数*/
  2. {
  3. ls=NULL;
  4. }

进栈运算

  1. void Push(LinkStack *&ls,ElemType x) /*进栈运算,ls为引用型参数*/
  2. {
  3. LinkStack *p;
  4. p=(LinkStack *)malloc(sizeof(LinkStack));
  5. p->data=x;
  6. p->next=ls;
  7. ls=p;
  8. }

出栈运算

  1. int Pop(LinkStack *&ls,ElemType &x) /*出栈运算,ls为引用型参数*/
  2. {
  3. LinkStack *p;
  4. if (ls==NULL) /*栈空,下溢出*/
  5. return 0;
  6. else
  7. {
  8. p=ls;
  9. x=p->data;
  10. ls=p->next;
  11. free(p);
  12. return 1;
  13. }
  14. }

取栈顶元素运算

  1. int GetTop(LinkStack *ls,ElemType &x) /*取栈顶元素运算*/
  2. {
  3. if (ls==NULL) /*栈空,下溢出*/
  4. return 0;
  5. else
  6. {
  7. x=ls->data;
  8. return 1;
  9. }
  10. }

判断栈空运算

  1. int StackEmpty(LinkStack *ls) /*判断栈空运算*/
  2. {
  3. if (ls==NULL)
  4. return 1;
  5. else
  6. return 0;
  7. }

main

  1. void main()
  2. {
  3. LinkStack *ls;
  4. ElemType e;
  5. InitStack(ls);
  6. printf("栈%s\n",(StackEmpty(ls)==1?"空":"不空"));
  7. printf("a进栈\n");Push(ls,'a');
  8. printf("b进栈\n");Push(ls,'b');
  9. printf("c进栈\n");Push(ls,'c');
  10. printf("d进栈\n");Push(ls,'d');
  11. printf("栈%s\n",(StackEmpty(ls)==1?"空":"不空"));
  12. GetTop(ls,e);
  13. printf("栈顶元素:%c\n",e);
  14. printf("出栈次序:");
  15. while (!StackEmpty(ls))
  16. {
  17. Pop(ls,e);
  18. printf("%c ",e);
  19. }
  20. printf("\n");
  21. }