#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;
}
栈的实现以及相关函数
最新推荐文章于 2024-09-16 18:31:59 发布