栈的链式实现0

本节介绍基本的数据结构:栈。以链式栈为例:

1)基本结构的定义:

typedef struct __stack stack;
typedef struct __node node;

struct __stack
{
	node *pNode;
	int  cursor;
	int  size;
};

struct __node
{
	struct __node *next;
	void *p_data;
};

2)基本操作:

/*
*	create a stack with initial value data.
*/
stack *create(void)
{
	stack *p_stack;
	node *p_node;
	
	p_stack = (stack *)malloc(sizeof(stack));
	if (p_stack == NULL)
	{
		perror("create stack failed!\n");
		return NULL;
	}

	p_stack->pNode  = NULL;
	p_stack->cursor = 0;
	p_stack->size   = 0;
	
	return p_stack;
}

//destory all node;
int destory_stack(stack *pStack)
{
	node *p;

	if (pStack == NULL)
		return 0;

	for (p = pStack->pNode; p != NULL; p = p->next)	
	{
		free(p->p_data);
		free(p);
	}

	free(pStack);

	return 0;
}

/*
*	Note: old type is pointer to pointer;
*/
#define ADD_NODE(old, new) do \
						 { (new)->next = (*old); (*old) = (new); }\
						 while(0) \

/*
*	push;
*/
int push(stack *pStack, void *data)
{
	node *p_node;
	
	if (pStack == NULL)
	{
		perror("stack invalid!\n");
		return -1;
	}

	if (pStack->size >= MAX_NODE)
	{
		perror("stack over flow!\n");
		return -1;
	}
 
	p_node = (node *)malloc(sizeof(node));
	if (p_node == NULL)
	{
		perror("push alloc node failed!\n");
		return -1;
	}

	p_node->p_data = (int *)malloc(sizeof(int));
	if (p_node->p_data == NULL)
	{
		perror("push alloc data space error!\n");
		free(p_node);		
		
		return 1;
	}

	*(int *)(p_node->p_data) = *(int *)data;

	ADD_NODE(&(pStack->pNode), p_node);

	pStack->size += 1;

	return 0;
}

/*
*	pop
*/
int pop(stack *pStack, void *out_data)
{
	node *p;	

	if (pStack == NULL || pStack->size == 0 || pStack->pNode == NULL)
	{
		//perror("pop stack error!\n");
		return -1;
	}
	
	p = pStack->pNode;

	*(int *)out_data = *(int *)(p->p_data);

	pStack->size -= 1;
	pStack->pNode = p->next;
	
	free(p->p_data);	
	free(p);
	
	return 0;
}

3)打印所有节点:

/*
* print out all node's data;
*/
int dump_stack(stack *pStack)
{
#define LINE_NUM 5
	
	node *p = NULL;
	int count = 0;
	
	if (pStack == NULL || pStack->size == 0 || pStack->pNode == NULL)
	{
		//perror("dump stack error!\n");
		return -1;
	}

	p = pStack->pNode;

	for ( ; p != NULL; p = p->next, ++ count)
	{
		if (count != 0 && count % LINE_NUM == 0)
			printf("\n");

		printf("%d\t", *(int *)(p->p_data));
	}

	printf("\n");		
	
	return 0;
}

至此,栈的简单实现完成。下一节讲述测试及说明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值