• 【数据结构】C语言栈的基本操作


    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    //定义节点
    struct Node
    {
        int data;
        struct Node *next;
    };
    typedef Node StackNode;
    //定义栈
     struct Stack
    {
        StackNode *top;
        StackNode *base;
    };
     typedef Stack SqStack;
     //定义创建栈的函数
     int InitStack(SqStack *S)
     {
         S->base = (StackNode*)malloc(sizeof(Node));
         if (!S->base)
         {
             printf("error");
             exit(1);
         }
         S->top = S->base;
    S->top->next=NULL;
    return 0; } //定义压栈函数 int PushStack(SqStack *S) { int e; StackNode *ps; ps = (StackNode *)malloc(sizeof(Node)); if (!ps) { printf("error"); exit(1); } printf("请输入你需要压入栈的数:"); scanf_s("%d", &e); ps->data = e; ps->next = S->top; S->top = ps; return 0; } //定义弹栈函数 int PopStack(SqStack *S) { int e; StackNode *ps; ps = S->top; S->top = S->top->next; e = ps->data; free(ps); return e; } //定义栈遍历函数 int TravelStack(SqStack *S) { StackNode *ps; ps = S->top; while (ps != S->base) { printf("数据为:%d ", ps->data); ps = ps->next; } return 0; } //定义判断栈是否为空函数 bool EmptyStack(SqStack *S) { StackNode *ps; ps = S->top; if (ps == S->base) { return true; } else { return false; } } //定义清空栈的函数 int ClearStack(SqStack *S) { StackNode *ps; ps = S->top; while (S->top != S->base) { S->top = S->top->next; free(ps); } return 0; } //主函数 int main() { int i,dec,input,DEC; SqStack *stack; stack = new Stack; InitStack(stack); do{ printf("请选择你需要的基本操作: "); printf("1************往栈中加入数据 "); printf("2************遍历该栈 "); printf("3************清空该栈 "); printf("4************删除栈顶元素 "); scanf_s("%d", &i); switch (i) { case 1: { printf("是否想往栈中输入数据?是选择1/否选择2 "); scanf_s("%d", &dec); while (dec == 1) { PushStack(stack); printf("是否继续输入数据?是选择1/否选择2 "); scanf_s("%d", &input); dec = input; } printf("你输入的数据为: "); TravelStack(stack); break; } case 2: { TravelStack(stack); break; } case 3: { ClearStack(stack); if (EmptyStack(stack)) { printf("该栈已经空!"); } else { printf("该栈不为空!"); }; break; } case 4: { int ReturnData; ReturnData = PopStack(stack); break; } } printf("是否要继续?是选择1/否选择2: "); scanf_s("%d", &DEC); } while (DEC == 1); }
  • 相关阅读:
    [CF1336C] Kaavi and Magic Spell
    [CF1338C] Perfect Triples
    [CF1353F] Decreasing Heights
    [CF1442B] Identify the Operations
    [CF1354E] Graph Coloring
    [CF1364D] Ehab's Last Corollary
    php-fpm和fastcgi的区别
    phpredis实现互斥锁
    关于lnmp情况下PHP单线程的理解
    客户端断开链接以后 PHP执行过程实测
  • 原文地址:https://www.cnblogs.com/code-wangjun/p/4356528.html
Copyright © 2020-2023  润新知