c语言之动态栈

本文介绍了C语言如何实现动态栈,探讨了栈这种先入后出的数据结构,并详细阐述了具体的实现过程。

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

栈:定义-一种以先入后出为存储数据方式的数据结构

 实现:

stack.h文件

#include <stdbool.h>

extern void push(char);
extern char pop();
extern bool is_empty();
extern bool is_ful();
extern void init_stack(int);
extern void destroy();

stack.c文件
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

static int top = 0;
static char *stack;
static int size = 512;
static int sz;

bool is_empty()
{
    return top == 0;
}

bool is_full()
{
    return top == sz;
}

void init_stack(int num)
{
    if(num <= 0)
        sz = size;
    else
        sz = num;
    stack = malloc(sz);
}


void push(char input)
{
    if(is_full())
    {
        printf("sz=%d---------\n",sz);
        stack = realloc(stack, sz*2);
        sz = sz * 2;
    }
    stack[top] = input;
    top++;
}

char pop()
{
    return stack[--top];
}

void destroy()
{
    free(stack);
}

test.c文件
#include <stdio.h>
#include "stack.h"

int main()
{
    char *str = "abcdefghigk";

    init_stack(3);

    while(*str != '\0')
    {
        push(*str);
        str++;
    }
    while(is_empty() == 0)
    {
        putchar(pop());
    }

    destroy();

    putchar('\n');

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值