栈 链式结构 C语言

这篇博客介绍了如何使用链式结构实现一个栈,并展示了压栈、出栈、查看栈顶元素和显示栈内所有元素的功能。通过一个C语言的实例,作者演示了将数字012345压入栈中,然后依次进行出栈操作,最后展示栈顶元素和当前栈内元素的过程。

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

由于是链式结构的栈,所以栈的容量基本上可是等于无限。

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

typedef int DataType;

typedef struct Node
{
	DataType data;
	int lengh;
	struct Node * next;
}Stack;

void init_stack(Stack *stack); 
//压栈 
void 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);
	printf("把元素0 1 2 3 4 5依次压进栈里\n");
	stack_push(&stack,0);
	stack_push(&stack,1);
	stack_push(&stack,2);
	stack_push(&stack,3);
	stack_push(&stack,4);
	stack_push(&stack,5);
	printf("显示目前栈内元素\n"); 
	show_stack(&stack);
	printf("出栈1次"); 
	stack_pop(&stack);
	printf("显示目前栈内元素\n"); 
	show_stack(&stack);
	printf("出栈2次"); 
	stack_pop(&stack);
	stack_pop(&stack);
	printf("显示目前栈内元素\n"); 
	show_stack(&stack);
	printf("目前栈顶元素为%d\n",get_top(&stack));
	return 0;	
} 

//初始化栈
void init_stack(Stack *stack)
{
	stack = (Stack *)malloc(sizeof(Stack));
	stack->next = NULL;
	stack->lengh = 0;
}
//压栈
void stack_push(Stack *stack, DataType data)
{
	Stack *p = (Stack *)malloc(sizeof(Stack));
	p->data = data;
	p->next = stack->next;
	stack->next = p;	
	stack->lengh ++;
}
//出栈 
bool stack_pop(Stack *stack)
{
	Stack *p = stack->next;
	if(stack->next == NULL)
	{
		printf("栈空\n");
		return false;
	}
	stack->next = p->next;
	free(p);
	stack->lengh --;
	return true;
}
//显示栈顶元素
DataType get_top(Stack *stack)
{
	if(stack->lengh == 0)
	{
		printf("栈空\n");
		return false;
	}
	else
		return stack->next->data;
}
//显示栈内的所有元素
bool show_stack(Stack *stack)
{
	if(stack->lengh == 0)
	{
		printf("栈空\n");
		return false;
	}
	Stack *p = stack;
	printf("[");
	for(int i = 0; i < stack->lengh; i++)
	{
		printf("%d, ",p->next->data);
		p = p->next;
	}
	printf("]\n");
}
main函数实现过程

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值