数据结构(第三天) 栈的顺序存储

本文通过C语言实现了一个简单的栈数据结构,并演示了如何进行基本的栈操作,如压栈(push)和弹栈(pop)等。文章提供了完整的源代码,并在主函数中通过一系列数值的压栈和弹栈操作展示了栈的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>

#define MAX 100

typedef struct 
{
    int buf[MAX];
    int top;
}seqstack;

seqstack *create_empty_seqstack()
{
    seqstack *s;

    s = (seqstack *)malloc(sizeof(seqstack));

    s->top = -1;

    return s;
}

int is_stack_full(seqstack *s)
{
    return s->top == MAX - 1 ? 1 : 0;
}

int push_stack(seqstack *s,int data)
{
#if 0
    if(s->top == MAX - 1)
    {
        printf("the stack is full\n");
        return -1;
    }
#endif 

    if(is_stack_full(s))
    {
        printf("the stack is full\n");
        return -1;
    }

    s->top ++;
    s->buf[s->top] = data;

    return 0;
}

int is_stack_empty(seqstack *s)
{
    return s->top == -1 ? 1 : 0;
}

int pop_stack(seqstack *s)
{
#if 0
    if(s->top == -1)
    {
        printf("the stack is empty\n");
        return -1;
    }
#endif

    if(is_stack_empty(s))
    {
        printf("the stack is empty\n");
        return -1;
    }

    int value;

    value = s->buf[s->top];
    s->top --;

    return value;
}

int main(int argc, const char *argv[])
{
    seqstack *s;

    s = create_empty_seqstack();

    int i;
    for(i = 1;i <= 5;i ++)
    {
        push_stack(s,i);
    }

//  while(s->top != -1)
    while(is_stack_empty(s) == 0)
    {
        printf("%d ",pop_stack(s));
    }
    printf("\n");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值