#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;
}
}
链栈的一系列操作
最新推荐文章于 2022-03-20 20:30:13 发布