C语言 建立简单的链表栈

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

#define TYPE int

typedef struct Node
{
	TYPE data;
	struct Node* next;
}Node;

Node* creat_node(TYPE data)
{
	Node* node = malloc(sizeof(Node));
	node->data=data;
	node->next = NULL;
	return node;
}

typedef struct Stack
{
	Node* top;
	size_t len;
}Stack;

//创建
Stack* creat_stack(void);
//销毁
void destory_stack(Stack* stack);
//栈空
bool empty_stack(Stack* stack);
//入栈
void push_stack(Stack* stack,TYPE data);
//出栈
bool pop_stack(Stack* stack);
//栈顶
TYPE* top_stack(Stack* stack);

//----------------以上为函数声明----------------

int main()//main函数用于测试
{
	Stack* stack = creat_stack();
	for(int i=0;i<10;i++)
	{
		push_stack(stack,i);
		printf("top:%d\n",*top_stack(stack));
	}
	printf("------------\n");
	for(int i=0;i<10;i++)
	{
		printf("top:%d  ",*top_stack(stack));
		printf("%s \n",pop_stack(stack)?"ok":"no");
	}
	

}

//------------------以下为实现函数------------------
//创建
Stack* creat_stack(void)
{
	Stack* stack = malloc(sizeof(Stack));
	stack ->top =NULL;
	stack ->len = 0;
	return stack;
}
//销毁
void destory_stack(Stack* stack)
{	
	while(pop_stack(stack));	
	free(stack);
}
//栈空
bool empty_stack(Stack* stack)
{
	return NULL == stack->top;	
}
//入栈
void push_stack(Stack* stack,TYPE data)
{
	Node* node = creat_node(data);
	node->next = stack->top;
	stack->top = node;	
	stack->len++;
}
//出栈
bool pop_stack(Stack* stack)
{
	if(empty_stack(stack)) return false;
	Node* node = stack->top;
	stack->top = node->next;
	free(node);
	stack->len--;
}
//栈顶
TYPE* top_stack(Stack* stack)
{
	if(empty_stack(stack))return NULL;
	return &stack->top->data;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值