栈的实现以及相关函数

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

typedef struct
{
    int *data;
    size_t length;
    size_t capacity;
} Stack;

void init_stack(Stack *stack, size_t init_capacity)
{
    stack->data = (int *)malloc(init_capacity * sizeof(int));
    stack->capacity = init_capacity;
    stack->length = 0;
}

void resize_stack(Stack *stack, size_t new_capacity)
{
    stack->data = (int*)realloc(stack,new_capacity * sizeof(int));
    stack->capacity = new_capacity;
}

void destroy_stack(Stack *stack)
{
    free(stack->data);
    stack->data = NULL;  // 重置为空指针
    stack->length = 0;   // 重置长度
    stack->capacity = 0; // 重置容量
}

size_t get_length(Stack *stack)
{
    return stack->length;
}

void push_stack(Stack *stack, int element)
{
    if (stack->length == stack->capacity)
    {
        resize_stack(stack, stack->capacity * 2);
    }
    stack->data[stack->length] = element;
    stack->length++;
}

bool pop_stack(Stack *stack, int *del_element)
{
    if (stack->length == 0)
    {
        return false;
    }
    *del_element = stack->data[stack->length - 1];
    stack->length--;
    return true;
}

void printf_stack(Stack *stack)
{
    if (stack->length == 0)
    {
        return;
    }
    for (size_t i = 0; i < stack->length; i++)
    {
        printf("%d ", stack->data[i]);
    }
    printf("\n");
}

int main()
{   Stack stack;
    init_stack(&stack,10);
    for (int i = 0; i < 10; i++)
    {
       push_stack(&stack,10+i);
    }
    printf_stack(&stack);
    int del_element;
    pop_stack(&stack,&del_element);
    printf("删除数值%d\n",del_element);
    printf_stack(&stack);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值