数据结构基础(2)-->栈

stack.h

#ifndef	STACK_H
#define	STACK_H		1
#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define	STACK_MAX		256

struct snode
{
	char		name[32];
	int		num;
	struct	snode	*next;
};

struct stack
{
	int		stacksize;
	struct	snode	*top;
};

struct stack *initstack(struct stack **stackhead);
void destroystack(struct stack **stackhead);
void clearstack(struct stack *stackhead);

int stackempty(const struct stack *stackhead);
int stacklength(const struct stack *stackhead);

int push(struct stack *stackhead, struct snode *entry);
struct snode *pop(struct stack *stackhead);
void printsnode(const struct snode *node);

#endif /* STATC_H */
stack.c

#include <stack.h>

/*
struct snode
{
	char		name[32];
	int		num;
	struct	node	*next;
};

struct stack
{
	int		stacksize;
	struct	node	*top;
};
//*/

struct stack *initstack(struct stack **stackhead)
{
	*stackhead = (struct stack *)malloc(sizeof(struct stack));
	if(!*stackhead) {
		return NULL;
	}
	(*stackhead)->stacksize = 0;
	(*stackhead)->top = NULL;
	return *stackhead;
}
void destroystack(struct stack **stackhead)
{
	clearstack(*stackhead);
	free(*stackhead);
	*stackhead = NULL;
	return;
}
void clearstack(struct stack *stackhead)
{
	while(NULL != pop(stackhead));
	return;
}

int stackempty(const struct stack *stackhead)
{
	return 0 == stackhead->stacksize;
}
int stacklength(const struct stack *stackhead)
{
	return stackhead->stacksize;
}

int push(struct stack *stackhead, struct snode *entry)
{
	if(STACK_MAX == stackhead->stacksize) {
		return -1;
	}
	entry->next = stackhead->top;
	stackhead->top = entry;
	++(stackhead->stacksize);
	return 0;
}
struct snode *pop(struct stack *stackhead)
{
	struct	snode *entry = NULL;
	if(stackhead->stacksize>0) {
		--(stackhead->stacksize);
		entry = stackhead->top;
		stackhead->top = entry->next;
		entry->next = NULL;
	}
	return	entry;
}
void printsnode(const struct snode *node)
{
	if(node) {
		printf("name=%10s, num=%3d...\n", node->name, node->num);
	} else {
		printf("node is NULL...\n");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值