链栈常规插入删除操作

素颜马尾好姑娘i 2022-12-13 11:20 261阅读 0赞
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef int DataType;
  4. struct Node
  5. {
  6. DataType data;
  7. struct Node*next;
  8. };
  9. typedef struct Node*PNode;//节点类型
  10. typedef struct Node*top,*LinkStack;//栈顶和链栈类型
  11. LinkStack SetNullStack_Link()//创建空链栈
  12. {
  13. LinkStack top=(LinkStack)malloc(sizeof(struct Node));
  14. if(top!=NULL)
  15. {
  16. top->next=NULL;
  17. }
  18. else
  19. {
  20. printf("alloc failure");
  21. }
  22. return top;
  23. }
  24. void Push_Link(LinkStack top,DataType x)//进栈,不需要判断链栈是否会溢出
  25. {
  26. PNode p=(PNode)malloc(sizeof(struct Node));//申请节点空间
  27. if(p==NULL)
  28. {
  29. printf("alloc failure");
  30. }
  31. else//相当于链表头插法
  32. {
  33. p->data=x;//数据域赋值
  34. p->next=top->next;//指针域赋值
  35. top->next=p;//修改栈顶
  36. }
  37. }
  38. int IsNullStack_Link(LinkStack top)//判断栈是否为空
  39. {
  40. if(top->next==NULL)
  41. return 1;
  42. else
  43. return 0;
  44. }
  45. void Pop_Link(LinkStack top)//删除栈顶元素,需要判空
  46. {
  47. PNode p;
  48. if(top->next==NULL)//判断栈是否为空
  49. printf("it is empty stack!");
  50. else
  51. {
  52. p=top->next;//p指向待删除的节点
  53. top->next=p->next;//修改栈顶指针
  54. free(p);//删除释放节点的空间
  55. }
  56. }
  57. DataType Pop_Link_Return(LinkStack top)//取栈顶元素
  58. {
  59. if(IsNullStack_Link(top)==1)//判断栈是否为空
  60. printf("it is empty stack!");
  61. else
  62. {
  63. return top->next->data;
  64. }
  65. }
  66. int main()
  67. {
  68. LinkStack p=SetNullStack_Link();//创建一个空栈
  69. int data;
  70. printf("请输入进栈的元素,以0结束:");
  71. scanf("%d",&data);
  72. while(data!=0)
  73. {
  74. Push_Link(p,data);//进栈
  75. scanf("%d",&data);
  76. }
  77. printf("出栈元素的顺序是:");
  78. while(!IsNullStack_Link(p))//是否空栈
  79. {
  80. printf("%d ",Pop_Link_Return(p));//取出栈顶元素
  81. Pop_Link(p);//出栈
  82. }
  83. }

输入输出样例如下
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,261人围观)

还没有评论,来说两句吧...

相关阅读

    相关 基本操作

    栈基本概念: 栈(stack)是限定在表尾进行插入和删除操作的线性表(或单链表)。 //只能在一段进行插入和删除,因此不存在,在中间进行插入 栈顶(top):允许插

    相关 表的插入删除

    【实验内容】: 设有两个无头结点的单链表,分别为ha,hb,其链中有数据域data,链域next,两链表的数据都按递增序存放。现要求将hb表归到ha表中,且归并后ha仍按递增