c语言链式栈

head.h
#include<io.h> /* eof() */
#include<math.h> /* floor(),ceil(),abs() */
#include<process.h> /* exit() */
/* 函数结果状态代码 */
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
/* #define OVERFLOW -2 因为在math.h中已定义OVERFLOW的值为3,故去掉此行 */
typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
typedef int Boolean; /* Boolean是布尔类型,其值是TRUE或FALSE */

typedef int SElemType;

typedef struct StackNode {

	SElemType data;
	struct StackNode *next;

}StackNode,*StackNodePosition;

typedef struct LinkStack
{
	StackNodePosition top;
	int count;
}LinkStack,*PLinkStack;

LinkStack *InitStack();		//构造一个空栈S
Status Destroy(LinkStack *S);		//销毁栈S
Status ClearStack(LinkStack *S);		//将S清为空栈
Status StackEmpty(LinkStack S);		//若栈S为空,则返回TRUE,否则返回FALSE
Status StackLength(LinkStack S);		//返回S的元素个数,既栈S的长度
Status GetTop(LinkStack S, SElemType *e);		//用e返回S的栈顶元素
Status Push(LinkStack *S, SElemType e);		//插入元素e为新的栈顶元素
Status Pop(LinkStack *S, SElemType *e);		//删除S的栈顶元素并用e返回其值
void StackTraverse(LinkStack S);		//从栈底一次输出S中的各个元素数据



FunctionOperate.c

#include "LinkListStack.h"

LinkStack *InitStack()		//构造一个空栈S
{
	LinkStack *S;
	S = (PLinkStack)malloc(sizeof(LinkStack));
	if (S == NULL)
		return ERROR;

	S->top = NULL;
	S->count = 0;

	return S;
}

Status Push(LinkStack *S, SElemType e)		//插入元素e为新的栈顶元素
{
	StackNode *newspace;
	newspace = (StackNode*)malloc(sizeof(StackNode));
	if (newspace == NULL)
	{
		return ERROR;
	}

	newspace->data = e;
	newspace->next = S->top;
	S->top = newspace;
	S->count++;
	return OK;
}

Status Destroy(LinkStack *S)		//销毁栈S
{
	StackNode *p = S->top;
	p = p->next;
	while (p != NULL)
	{
		free(S->top);
		S->top = p;
		p = p->next;
	}

	free(S->top);
	S->count = NULL;

	return OK;
}

Status ClearStack(LinkStack *S)		//将S清为空栈
{
	StackNode *p = S->top;
	p = p->next;
	while (p != NULL)
	{
		free(S->top);
		S->top = p;
		p = p->next;
	}

	S->count = 0;
}

Status StackEmpty(LinkStack S)		//若栈S为空,则返回TRUE,否则返回FALSE
{
	if (S.count == 0 || !S.top)
		return TRUE;
	else
		return FALSE;
		
}

Status StackLength(LinkStack S)		//返回S的元素个数,既栈S的长度
{
	return S.count;
}

Status GetTop(LinkStack S, SElemType *e)		//用e返回S的栈顶元素
{
	if (S.top==NULL)
		return ERROR;
	
	*e = S.top->data;
	return OK;
}

Status Pop(LinkStack *S, SElemType *e)		//删除S的栈顶元素并用e返回其值
{
	StackNode *p;
	if (S->top == NULL)
		return ERROR;

	*e = S->top->data;
	p = S->top;
	S->top = S->top->next;
	S->count--;
	free(p);

	return OK;

}

void StackTraverse(LinkStack S)
{
	if (S.top == NULL)
		return ERROR;

	while (S.top != NULL)
	{
		printf(" %d ",S.top->data);
		S.top = S.top->next;
	}
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值