重学数据结构003——栈的基本操作及实现(链式存储)

1.栈的概念

展示只允许在其一端进行插入语删除操作的表。从定义上来说,栈其实也是线性表,因此栈也具备大多数线性表所具备的基本操作。但是,从定义上可知,栈在进行插入、删除操作时,只能在一端进行操作,这一端成为栈顶(top)。

栈最核心的操作主要是:进栈(Push)、出栈(Pop)、返回栈顶元素(Top)。 此外,栈还判断栈是否为空、创见栈、清空栈等操作。

既然是线性表,那么栈从实现方式来说主要有两种:顺序存储实现(数组)、链式存储实现(链表)。下面是链式存储实现方式下,站的数据结构定义:

 
  1. typedefstructNode*PtrToNode;
  2. typedefPtrToNodeStack;
  3. typedefstructNode
  4. {
  5. intElement;
  6. PtrToNodeNext;
  7. };

站的基本操作如下:

 
  1. //判断栈是否为空
  2. intIsEmpty(StackS);
  3. //创见栈
  4. StackCreateStack();
  5. //销毁栈
  6. voidDisposeStack(StackS);
  7. //清空栈
  8. voidMakeEmpty(StackS);
  9. //进栈
  10. voidPush(intX,StackS);
  11. //返回栈顶元素
  12. intTop(StackS);
  13. //出栈
  14. voidPop(StackS);

下面是一个完整的关于栈的基本操作的例子:

 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedefstructNode*PtrToNode;
  4. typedefPtrToNodeStack;
  5. typedefstructNode
  6. {
  7. intElement;
  8. PtrToNodeNext;
  9. };
  10. intIsEmpty(StackS);
  11. StackCreateStack();
  12. voidDisposeStack(StackS);
  13. voidMakeEmpty(StackS);
  14. voidPush(intX,StackS);
  15. intTop(StackS);
  16. voidPop(StackS);
  17. //判断栈是否为空
  18. intIsEmpty(StackS)
  19. {
  20. returnS->Next==NULL;
  21. }
  22. //创建链栈
  23. StackCreateStack()
  24. {
  25. StackS=malloc(sizeof(structNode));
  26. if(S==NULL)
  27. {
  28. printf("Noenoughmemory!");
  29. returnNULL;
  30. }
  31. S->Next=NULL;
  32. MakeEmpty(S);
  33. returnS;
  34. }
  35. voidMakeEmpty(StackS)
  36. {
  37. if(S==NULL)
  38. {
  39. printf("UseCreateStackFirst!");
  40. }
  41. else
  42. {
  43. while(!IsEmpty(S))
  44. {
  45. Pop(S);
  46. }
  47. }
  48. }
  49. voidPush(intX,StackS)
  50. {
  51. PtrToNodeTmp;
  52. Tmp=malloc(sizeof(structNode));
  53. if(Tmp!=NULL)
  54. {
  55. Tmp->Element=X;
  56. Tmp->Next=S->Next;
  57. S->Next=Tmp;
  58. }
  59. else
  60. {
  61. printf("Outofspace!");
  62. }
  63. }
  64. voidPop(StackS)
  65. {
  66. if(IsEmpty(S))
  67. {
  68. printf("TheStackisEmpty!");
  69. }
  70. else
  71. {
  72. PtrToNodeTmp=S->Next;
  73. S->Next=Tmp->Next;
  74. free(Tmp);
  75. }
  76. }
  77. intTop(StackS)
  78. {
  79. if(IsEmpty(S))
  80. {
  81. printf("Thestackisempty!");
  82. return0;
  83. }
  84. else
  85. {
  86. returnS->Next->Element;
  87. }
  88. }
  89. intmain(void)
  90. {
  91. StackS=CreateStack();
  92. inti;
  93. for(i=0;i<5;i++)
  94. {
  95. Push(i,S);
  96. }
  97. while(!IsEmpty(S))
  98. {
  99. printf("%d\n",Top(S));
  100. Pop(S);
  101. }
  102. return0;
  103. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值