c语言:链栈的实现

#include
#include
#include
#define LEN sizeof(struct LNode)
using namespace std;
typedef struct LNode
{
	int data;
	struct LNode *next;
}LNode;
typedef struct LinkStack
{
	LNode *top;
}LinkStack;
//函数申明
void Error(char *s);             //错误处理函数
void Gettop_stack(LinkStack *s, int e); //取栈顶元素
int Empty_stack(LinkStack *s);    //判断该链栈是否为空
void Push_stack(LinkStack *s, int e);   //压栈函数
void Pop_stack(LinkStack *s, int e);     //出栈函数

//函数定义
void Error(char *s)
{
	cout << s << endl;
	exit(1);
}
void Gettop_stack(LinkStack *s, int e)
{
	if (s->top == NULL)
		Error("该链栈为空栈!");
	else
		e = s->top->data;
	cout << "该栈顶元素是:" << e << endl;
}
int Empty_stack(LinkStack *s)
{
	if (s->top == NULL)
		return 1;
	else
		return 0;
}
void Push_stack(LinkStack *s, int e)
{
	LNode *p;
	p = (struct LNode*)malloc(LEN);
	if (!p)
		Error("内存分配失败");
	p->data = e;
	p->next = s->top;
	s->top = p;
}
void Pop_stack(LinkStack *s, int e)
{
	LNode *p;
	if (s->top==NULL)
		exit(1);
	e = s->top->data;
	p = s->top;
	s->top = s->top->next;
	cout << e << " ";
	free(p);
}

int main()
{
	LinkStack p;
	p.top = NULL;
	int e = 0;
	Push_stack(&p, 9);
	Push_stack(&p, 8);
	Push_stack(&p, 11);
	while (p.top != NULL)
	{
		Pop_stack(&p, e);
	}
	cout << endl;
	return 0;
}

你可能感兴趣的:(数据结构与算法设计)