顺序栈和链栈的基本操作

本是古典 何须时尚 2023-07-10 15:58 65阅读 0赞

1. 顺序栈

  1. #include<stdio.h>
  2. //进栈,进栈元素为elem,top值为栈顶 ,a为数组
  3. int push(int *a,int top,int elem){
  4. a[++top]=elem;
  5. return top;
  6. }
  7. //出栈
  8. int pop(int *a,int top){
  9. if(top==-1)
  10. {
  11. printf("空栈!!!\n");
  12. return -1;
  13. }
  14. printf("出栈元素为:%d\n",a[top]);
  15. top--;
  16. return top;
  17. }
  18. main(){
  19. int a[100];
  20. int top=-1;
  21. pop(a,top);
  22. top=push(a,top,1);
  23. top=push(a,top,100);
  24. top=push(a,top,999);
  25. top=pop(a,top);
  26. top=pop(a,top);
  27. top=pop(a,top);
  28. }

2.链栈

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedef struct lineStack{
  4. int data;
  5. struct lineStack *next;
  6. }lineStack;
  7. //进栈操作
  8. lineStack* push(lineStack *stack,int elem){
  9. //创建存储新元素的结点
  10. lineStack *line=(lineStack*)malloc(sizeof(lineStack));
  11. //将进栈元素赋值给新结点line
  12. line->data=elem;
  13. //新结点与头结点建立逻辑关系,新结点指向头结点
  14. line->next=stack;
  15. //跟新栈顶位置
  16. stack=line;
  17. //返回栈顶位置
  18. return stack;
  19. }
  20. //入栈操作
  21. lineStack* pop(lineStack *stack){
  22. //判断原栈是否为空
  23. if(stack){
  24. //声明一个新指针指向头结点(栈顶结点)
  25. lineStack *p=stack;
  26. //跟新栈顶结点
  27. stack=stack->next;
  28. printf("出栈的元素为:%d\n",p->data);
  29. //判断新栈是否为空
  30. if(stack){
  31. printf("栈顶元素为:%d\n",stack->data);
  32. }else
  33. {
  34. printf("栈已空!!!\n");
  35. }
  36. //释放空间
  37. free(p);
  38. } else
  39. {
  40. printf("栈内没有元素!!!\n");
  41. return stack;
  42. }
  43. return stack;
  44. }
  45. main()
  46. {
  47. //创建一个空结点
  48. lineStack *stack=NULL;
  49. //将元素1进栈
  50. stack=push(stack,1);
  51. //将元素520进栈
  52. stack=push(stack,520);
  53. //将元素999进栈
  54. stack=push(stack,999);
  55. //出栈(先进后出)
  56. stack=pop(stack);
  57. stack=pop(stack);
  58. stack=pop(stack);
  59. stack=pop(stack);
  60. }

发表评论

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

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

相关阅读

    相关 基本操作

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