C 数据结构:栈的链式存储

本文详细介绍了如何使用C语言实现链式存储的栈数据结构。从初始化、入栈、出栈到销毁,每一步都有详细的代码示例。通过一个简单的程序演示了栈的基本操作。

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

C 数据结构:栈的链式存储

一、实现
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int  data_;
	struct node* next_;
}Node;
typedef struct stack
{
	Node *top_;
}Stack;

void initStack(Stack *stack);
void push(Stack *stack, int data);
int pop(Stack *stack);
int isEmpty(Stack *stack);
void destoryStack(Stack *stack);

int main()
{
	Stack s;
	initStack(&s);
	for (int i = 0; i<4; ++i)
	{
		push(&s, i);
	}
	while (!isEmpty(&s))
		printf("%2d", pop(&s));
	puts("");
	destoryStack(&s);
	return 0;
}

void initStack(Stack *stack)
{
	stack->top_ = (Node*)malloc(sizeof(Node));
	if (NULL == stack->top_)
		exit(-1);
	stack->top_->next_ = NULL;
}
void push(Stack *stack, int data)
{
	Node *ptr = (Node*)malloc(sizeof(Node));
	if (NULL == ptr)
		exit(-1);
	ptr->data_ = data;
	ptr->next_ = stack->top_->next_;
	stack->top_->next_ = ptr;
}
int pop(Stack *stack)
{
	Node *tmp = stack->top_->next_;
	int tmpData = tmp->data_;
	stack->top_->next_ = tmp->next_;
	free(tmp);
	tmp = NULL;
	return tmpData;
}
int isEmpty(Stack *stack) { return NULL == stack->top_->next_; }
void destoryStack(Stack *stack)
{
	while (!isEmpty(stack))
		pop(stack);
	free(stack->top_);
	stack->top_ = NULL;
}

在这里插入图片描述

二、过程演示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值