栈 结构 数组实现 C语言

本文介绍了如何使用C语言实现一个基于数组的栈,包括初始化、判断栈空栈满、压栈、出栈、获取栈顶元素及显示栈内所有元素等基本操作。栈在初始化时指定最大容量,并通过malloc()函数动态分配内存以实现扩容。示例代码展示了栈的增删查改过程。

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

栈 

由于使用数组写的,所以初始化的时候需要给定栈的容量大小,需要考虑栈是否满的情况,其实数组也是可以写像链式栈那种不会满的特性的, 可以直接通过malloc()函数来进行扩容, 我上一篇博客顺序表就实现了这个功能。

#include<stdio.h>
#include<stdlib.h>
typedef int DataType;

typedef struct{
	DataType *data;
	int MaxSize;
	int top;
}Stack;

//初始化栈
void init_stack(Stack *stack, int Max);
//判断栈是否为空
bool is_empty(Stack *stack);
//判断栈是否满 
bool is_full(Stack *stack);
//压栈
bool stack_push(Stack *stack, DataType data);
//出栈
bool stack_pop(Stack *stack);
//获取栈顶元素
DataType get_top(Stack *stack); 
//显示栈的所有元素 
bool show_stack(Stack *stack);
int main()
{
	Stack stack;
	init_stack(&stack,6);
	stack_push(&stack,0);
	stack_push(&stack,1);
	stack_push(&stack,2);
	stack_push(&stack,3);
	stack_push(&stack,4);
	stack_push(&stack,5);
	stack_push(&stack,6);
	show_stack(&stack);
	stack_pop(&stack);
	stack_pop(&stack);
	show_stack(&stack);
	stack_pop(&stack);
	stack_pop(&stack);
	stack_pop(&stack);
	stack_pop(&stack);
	stack_pop(&stack);
	show_stack(&stack);
	stack_push(&stack,6);
	show_stack(&stack);
	printf("%d", get_top(&stack)) ;
	return 0;	
} 

//初始化栈
void init_stack(Stack *stack, int Max)
{
	stack->MaxSize = Max;
	stack->data = (DataType*)malloc(sizeof(DataType) * Max);
	if(stack->data == NULL)
	{
		printf("栈内存分配失败\n");
		exit(-1);
	}
	stack->top = -1;
	return;
}
//判断栈是否为空
bool is_empty(Stack *stack)
{
	if(stack->top == -1)
		return true;
	else
		return false;
}
//判断栈是否满 
bool is_full(Stack *stack)
{
	if(stack->top >= stack->MaxSize - 1)
		return true;
	else
		return false;
}
//压栈
bool stack_push(Stack *stack, DataType data)
{
	if(is_full(stack))
	{
		printf("栈满,不能添加元素\n");
		return false;
	}
	stack->top ++;
	stack->data[stack->top] = data;
	return true;
}
//出栈
bool stack_pop(Stack *stack)
{
	if(is_empty(stack))
	{
		printf("栈空,不能出栈元素\n");
		return false;
	}
	stack->top --;
	return true;
}

//获取栈顶元素
DataType get_top(Stack *stack)
{
	return stack->data[stack->top];
}
//显示栈的所有元素 
bool show_stack(Stack *stack)
{
	if(is_empty(stack))
	{
		printf("栈空,没有元素\n");
		return false;
	}
	printf("[");
	for(int i = 0; i <= stack->top; i++)
	{
		printf("%d, ",stack->data[i]);
	}
	printf("]\n");
	return true;
}
代码中的main函数运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值