• 栈实现 C语言


    最近上来写了一下栈,理解数据结构的栈。

    头文件:stack.h

    初始化栈结构与函数定义:

    #include<stdlib.h>
    #include <stdio.h>
    #include<memory.h>
    #define N 100
    
    struct  stack
    {
        int data[N];
        int top;//标识栈顶
    }; 
    
    typedef struct  stack  Stack;//Stack别名
    
    void init(Stack * p);//初始化
    int  isempty(Stack * p);//判定栈是否空
    int isfull(Stack * p);//判定栈溢出
    int  gettop(Stack * p);//获取栈顶
    void push(Stack * p, int key);//插入数据
    void pop(Stack * p);//吐出
    void  show(Stack * p);//显示栈

    stack.c

    实现函数:初始化,判断栈顶,溢出等

    #include "stack.h"
    
    void init(Stack * p)//初始化
    {
        p->top = -1;//代表为空
        memset(p->data, 0, sizeof(int)*N);//数据清零
    
    }
    int  isempty(Stack * p)//判定栈是否空
    {
        if (p->top==-1)
        {
            return 1;//1为空
        } 
        else
        {
            return 0;//0不为空
        }
    }
    int isfull(Stack * p)//判定栈溢出
    {
        if (p->top==N-1)
        {
            return 1;///溢出
        } 
        else
        {
            return 0;//还能再喝点
        }
    }
    int  gettop(Stack * p)//获取栈顶
    {
        return p->data[p->top];//获取栈顶
    }
    void push(Stack * p, int key)//插入数据
    {
        if (isfull(p)==1)
        {
            return;
        } 
        else
        {
            p->top += 1;
            p->data[p->top] = key;//压入数据
        }
    }
    void pop(Stack * p)//吐出
    {
        if (isempty(p)==1)
        {
            return;
        } 
        else
        {
            p->top -= 1;//出栈
        }
    }
    
    void  show(Stack * p)
    {
        int i;
        if (isempty(p) == 1)
        {
            return;
        }
        else
        {
            printf("
    栈的数据是
    ");
            for (i = 0; i <= p->top;i++)
            {
                printf("%4d", p->data[i]);//打印栈的数据
            }
            
            printf("
    ");
        }
    }

    主函数main.c

    #include<stdio.h>
    #include"stack.h"
    void main()
    {
        int i = 0;
        int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    
        Stack mystack;
        init(&mystack);//初始化
        for (i = 0; i < 10;i++)
        {
            push(&mystack, i);
        }
        //全部装完再吐
        while (!isempty(&mystack))
        {
            printf("%d", gettop(&mystack)); //获取栈顶
            pop(&mystack); //吐出
        }
    
        printf("
    ");
    
        //装一个吐一个。。。。。
        init(&mystack);//初始化
        for (i = 0; i < 10; i++)
        {
            push(&mystack, i);
            printf("%d", gettop(&mystack));
            pop(&mystack);
        }
        getchar();
    }
  • 相关阅读:
    移动端 细节点
    基于新版 node 的 vue 脚手架搭建
    全屏展示
    Vue 小实例
    移动端 模拟键盘 盖住表单
    decodeURI decodeURIComponent
    简单时钟
    全选 反选 传统写法
    星级点评 面向过程的传统写法
    JQ字符串截取
  • 原文地址:https://www.cnblogs.com/zhenghongxin/p/6734762.html
Copyright © 2020-2023  润新知