链栈的一系列操作

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
typedef bool Status;
typedef struct node
{
	ElemType data;
	node* next;
}Node,*pNode;
typedef struct stack
{
	pNode pTop;
	pNode pBase;
}Stack,*pStack;
void Init(pStack);
void Push(pStack,ElemType);
void Traverse(pStack);
Status Pop(pStack,ElemType*);
Status Clear(pStack);
Status IsEmpty(pStack);
Status GetTop(pStack,ElemType*);
int main()
{
	Stack St;ElemType val;
	Init(&St);
	if(IsEmpty(&St))cout<<"The stack is empty"<<endl;

	Push(&St,1);
	Push(&St,2);
	Push(&St,3);
	Push(&St,4);
	Traverse(&St);
	if(IsEmpty(&St))cout<<"The stack is empty"<<endl;
	else cout<<endl;

	if(GetTop(&St,&val))cout<<"The top of the stack is "<<val<<"."<<endl;
	else cout<<"The stack maybe is empty."<<endl;

	if(Pop(&St,&val))cout<<"The top data of stack has popped, the data is "<<val<<"."<<endl;
	else cout<<"Your Operator is error!"<<endl;
	Traverse(&St);

	if(Clear(&St))cout<<endl<<"The Stack has cleaned."<<endl;
	else cout<<"The stack maybe is empty."<<endl;
	Traverse(&St);
}
void Init(pStack st)
{
	st->pTop=(pNode)malloc(sizeof(Node));
	if(st->pTop==0)
	{
		cout<<"The stack has not initiate"<<endl;exit(-1);
	}
	st->pBase=st->pTop;
	st->pTop->next=NULL;
}
void Push(pStack st,ElemType val)
{
	pNode pNew=(pNode)malloc(sizeof(Node));
	if(pNew==0)exit(-1);
	pNew->data=val;
	pNew->next=st->pTop;
	st->pTop=pNew;
}
void Traverse(pStack st)
{
	if(!IsEmpty(st))
	{
		pNode p=st->pTop;
		while(p!=st->pBase)
		{
			cout<<p->data<<" ";
			p=p->next;
		}
	}
	else
	{
		cout<<"The stack is empty."<<endl;
	}
}
Status Pop(pStack st,ElemType* val)
{
	if(!IsEmpty(st))
	{
		pNode q=st->pTop;
		*val=q->data;
		st->pTop=q->next;
		free(q);
		q=NULL;
		return true;
	}
	else
	{
		cout<<"The stack is empty."<<endl;
		return false;
	}
}
Status Clear(pStack st)
{
	if(!IsEmpty(st))
	{
		pNode p=st->pTop,q=NULL;
		while(p!=st->pBase)
		{
			q=p->next;
			free(p);
			p=q;
		}
		st->pTop=st->pBase;
		return true;
	}
	else
	{
		cout<<"The stack is empty"<<endl;
		return false;
	}
}
Status IsEmpty(pStack st)
{
	if(st->pBase==st->pTop)return true;
	else return false;
}
Status GetTop(pStack st,ElemType* val)
{
	if(!IsEmpty(st))
	{
		*val=st->pTop->data;
		return true;
	}
	else
	{
		cout<<"The stack is empty."<<endl;
		return false;
	}
}

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值