栈(C语言)超级简洁版

数据结构设计:

typedef struct stack_node
{
	struct stack_node* next;
	void* data;
}stack_node;

typedef struct stack
{
	struct stack_node* top;
	int length;
}stack;

接口:

//创建栈
stack* createStack();
//入栈
stack* stack_push(stack* stack, void* data);
//出栈
void* stack_pop(stack* stack);
//清空栈中所有元素
void stack_empty(stack* stack);
//删除栈
void stack_release(stack* stack);

接口实现:

stack *createStack()
{
	stack* stack = (struct stack*)malloc(sizeof(struct stack));
	if (stack == NULL)
		return NULL;
	stack->top = NULL;
	stack->length = 0;
	return stack;
}

stack* stack_push(stack* stack,void* data)
{
	stack_node* newNode = (struct stack_node*)malloc(sizeof(struct stack_node));
	if (newNode == NULL)
		return NULL;
	newNode->data = data;
	
	newNode->next = stack->top;
	stack->top = newNode;

	stack->length++;
	return stack;
}
void* stack_pop(stack* stack)
{
	if (stack == NULL)
		return NULL;
	stack_node* cur = stack->top;
	if (cur == NULL)
		return NULL;
	void* data = cur->data;
	stack->top = cur->next;
	free(cur);
	stack->length--;
	return data;
}

void stack_empty(stack* stack)
{
	if (stack == NULL)
		return ;

	stack_node* cur;
	stack_node* next;
	
	cur = stack->top;
	while (stack->length--)
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
	stack->length = 0;
	stack->top = NULL;
	return;
}

void stack_release(stack* stack)
{
	stack_empty(stack);
	free(stack);
	return;
}

测试:

int main()
{
	char a = 'a';
	char b = 'b';
	char c = 'c';

	//创建栈
	stack* stack = createStack();
	printf("%p\n", stack_pop(stack));

	//压栈
	stack_push(stack, &a);
	stack_push(stack, &b);
	stack_push(stack, &c);
	
	//出栈
	while (stack->length>0)
	{
		printf("%c\n", *(char*)stack_pop(stack));
	}

	//压栈出栈
	stack_push(stack, &a);
	stack_empty(stack);
	printf("%p\n",stack_pop(stack));

	//删除栈
	stack_release(stack);

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值