链栈的实现(单指针 无头结点) C语言版

 
/*
	单指针指向、无头结点的链栈
	作者:S_hmily
	日期:2011年8月31日
	编译环境:VC++6.0
*/
/*********************************************************/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
/*********************************************************/
#define OK      1         
#define ERROR   0         
#define TRUE    1         
#define FALSE   0       
typedef int     ElemType;    
typedef int     Status; 

typedef struct node {
	ElemType	data;
	struct node	*next;
}StackNode, *pStackNode;

typedef struct {
	pStackNode	top;
	int			count;
}LinkStack;
/*********************************************************/
//初始化
Status InitLinkStack(LinkStack *S)
{
	S->top = NULL;
	S->count = 0;
	return OK;
}
/*********************************************************/
//压栈
Status PushStack(LinkStack *S, ElemType e)
{
	pStackNode pNew = (pStackNode)malloc(sizeof(StackNode));
	pNew->data = e;
	pNew->next = S->top;
	S->top = pNew;
	++S->count;
	return OK;
}
/*********************************************************/
//出栈
Status PopStack(LinkStack *S, ElemType *e)
{
	pStackNode p = S->top;
	if (NULL == S->top)
		return ERROR;

	*e = p->data;
	S->top = S->top->next;
	free(p);
	--S->count;
	return OK;
}
/*********************************************************/
//打印栈中元素
void DispLinkStack(LinkStack *S)
{
	pStackNode p = S->top;

	while (p)
	{
		printf("%d ", p->data);
		p = p->next;
	}
}
/*********************************************************/
int main(void)
{
	LinkStack S;
	ElemType e;
	InitLinkStack(&S);
	PushStack(&S, 1);
	PushStack(&S, 2);
	PushStack(&S, 3);
	PushStack(&S, 4);
	PushStack(&S, 5);
	DispLinkStack(&S);
	PopStack(&S, &e);
	PopStack(&S, &e);
	PopStack(&S, &e);
	PopStack(&S, &e);
	PopStack(&S, &e);
	printf("\n\n%d ", e);
	DispLinkStack(&S);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值