• 使用链表实现栈操作


    源码如下:

    1. #include
    2. #include
    3. struct node
    4. {
    5. int info;
    6. struct node *link;
    7. };
    8. struct node *top = NULL, *temp;
    9. void push(struct node *);
    10. void pop(struct node *);
    11. void display(struct node *);
    12. int main()
    13. {
    14. int x = 0, item;
    15. printf("\t****stack using linked list****\n");
    16. while (x != 4)
    17. {
    18. printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
    19. printf("Enter your choice: ");
    20. scanf("%d", &x);
    21. switch (x)
    22. {
    23. case 1:
    24. push(top);
    25. break;
    26. case 2:
    27. pop(top);
    28. break;
    29. case 3:
    30. display(top);
    31. break;
    32. case 4:
    33. return 0;
    34. }
    35. }
    36. }
    37. void push(struct node *p)
    38. {
    39. int item;
    40. struct node *temp;
    41. temp = (struct node *)malloc(sizeof(struct node));
    42. printf("\nEnter element to be inserted: ");
    43. scanf("%d", &item);
    44. temp->info = item;
    45. temp->link = top;
    46. top = temp;
    47. printf("Inserted succesfully.\n");
    48. }
    49. void pop(struct node *p)
    50. {
    51. int item;
    52. struct node *temp;
    53. if (top == NULL)
    54. printf("\nStack is empty.\n");
    55. else
    56. {
    57. item = top->info;
    58. temp = top;
    59. top = top->link;
    60. free(temp);
    61. printf("\nElement popped is %d.\n", item);
    62. }
    63. }
    64. void display(struct node *p)
    65. {
    66. if (top == NULL)
    67. printf("\nStack is empty.\n");
    68. else
    69. {
    70. printf("\nElements in the stack are:\n");
    71. while (p != NULL)
    72. {
    73. printf("\t%d\n", p->info);
    74. p = p->link;
    75. }
    76. // printf("%d\n",p->info);
    77. }
    78. }

    测试运行:

        ****stack using linked list****

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 1

    Enter element to be inserted: 88 //入栈
    Inserted succesfully.

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 3

    Elements in the stack are:
        88

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 1

    Enter element to be inserted: 22 //入栈
    Inserted succesfully.

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 3

    Elements in the stack are:
        22
        88

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 2

    Element popped is 22. //出栈

    1. Push
    2. Pop
    3. Display
    4. Exit
    Enter your choice: 3

    Elements in the stack are:
        88
     

  • 相关阅读:
    【图像处理】基于图像聚类的无监督图像排序问题(Matlab代码实现)
    React源码分析4-深度理解diff算法
    Java容器详解(浅层)
    ElasticSearch
    面试题总结第二弹
    Cy3.5-PEG-DPSE,Cy3.5-聚乙二醇-磷脂,DPSE-PEG-Cy3.5
    基于ERP集成的流程制造管理系统
    【软件工程】看板
    【每日一题】移除链表元素(C语言)
    LC-895. 最大频率栈(优先队列+哈希表)
  • 原文地址:https://blog.csdn.net/qq_20490175/article/details/134021305