C语言一一如何实现一个栈

前言
栈是一种数据结构,例如函数的调用就需要使用栈。栈的特点是先进后出,可以想象成子弹夹子。当上子弹时候,最晚放上去的,可以最先拿出来。由于栈只有一边开口存取数据,称开口的那一端为“栈顶”,封死的那一端为“栈底”。栈的结构图如下:

在这里插入图片描述

栈的先进后出原则

数据按一定的顺序存储到栈中,当需要调取栈中某数据元素时,需要将在该数据元素之后进栈的先出栈,该数据元素才能从栈中提取出来。
例如栈的结构图中:
存放了 4 个数据元素,进栈的顺序是 1先进栈,然后 2 进,然后 3 进,最后4 进栈;当需要调取 1 时,首先 4 出栈,然后3 出栈,然后2 出栈,最后 1 才能出栈被调用。

栈的操作
栈的常见操作有出栈,也称“弹栈”,从栈中弹出一个元素;入栈,也叫“压栈”,将一个元素压入栈中,访问栈顶元素,判断栈是否为空等。

栈的实现
我们可以选择数组或者链表来实现栈,数组来存储栈元素预先申请连续的存储单元。容量有限且固定,但操作简单。链表的操作并不如数组方便,每次入栈要进行内存申请,出栈要释放内存,稍有不慎便造成内存泄露。接来下用数组实现栈。

数组实现栈

在数组栈中设定一个随时指向栈顶元素的变量(top ),当 top 的值为 -1 时,说明数组中没有数据,即栈中没有数据元素,为“空栈”;只要数据元素进栈,top 就加 1 ;数据元素出栈, top 就减 1 。

#include <stdio.h>

#define STACK_SIZE 64  //栈大小
#define TOP_OF_STACK -1 //栈顶位置

int stack_push(char* stack,int top,int value);
int stack_pop(char * stack,int top);
int stack_is_empty(int top);
int stack_is_full(int top);

//入栈
int stack_push(char* stack,int top,int value)
{
    if (stack_is_full(top)) 
    {
        printf("栈满\n");
        return -1;
    }

    stack[++top]=value;
    printf("入栈元素:%d\n",stack[top]);
    return top;
}

//出栈
int stack_pop(char * stack,int top)
{
    if (stack_is_empty(top)) 
    {
        printf("空栈\n");
        return -1;
    }
    printf("出栈元素:%d\n",stack[top]);
    top--;
    return top;
}

int stack_is_empty(int top)
{
    return top ==  - 1;
}

int stack_is_full(int top)
{
    return top == STACK_SIZE - 1;
}


int main(int argc, char **argv) 
{
    char stack[100];
    int top = TOP_OF_STACK;  //栈顶位置
    top=stack_push(stack, top, 1);
    top=stack_push(stack, top, 2);
    top=stack_push(stack, top, 3);
    top=stack_push(stack, top, 4);

    top=stack_pop(stack, top);
    top=stack_pop(stack, top);
    top=stack_pop(stack, top);
    top=stack_pop(stack, top);
    top=stack_pop(stack, top);

    return 0;
}




输出结果:

在这里插入图片描述

发布了71 篇原创文章 · 获赞 42 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chen1415886044/article/details/102732518