您的位置:首页 > 其它

堆栈之链表实现

2014-09-24 22:56 176 查看
#include<iostream>
using namespace std;
struct LinktackNode
{
LinktackNode* lastIn;
int value;
};
struct LinkStack
{
LinktackNode* top;
LinktackNode* bottom;
bool isEmpty;
int cnt;
};
LinkStack* createLinkStack()
{
LinkStack* st = (LinkStack*)malloc(sizeof(LinkStack));
LinktackNode* temp = (LinktackNode*)malloc(sizeof(LinktackNode));
temp->lastIn=NULL;
st->top=temp;
st->bottom=temp;
st->cnt=0;
st->isEmpty=true;
return  st;
}

bool isEmpty(LinkStack* st)
{
return st->isEmpty;
}

void push(LinkStack* st,int value)
{
LinktackNode* inNode = (LinktackNode*)malloc(sizeof(LinktackNode));
inNode->lastIn=st->top;
inNode->value=value;
st->top=inNode;
st->isEmpty =((++st->cnt)==0);
}
bool pop(LinkStack* st,int* ans)
{
if(!st->isEmpty)
{
*ans=st->top->value;
st->top=st->top->lastIn;
st->isEmpty =((--st->cnt)==0);
return 1;
}
return 0;
}
bool top(LinkStack* st,int* ans)
{
if(!st->isEmpty)
{
*ans=st->top->value;
return 1;
}
return 0;
}
void clearStack(LinkStack* st)
{
int x;
while(!st->isEmpty)
{
pop(st,&x);
cout<<x<<" ";
}
cout<<endl;
}

void outPut(LinkStack* st)
{
LinktackNode* p = st->top;
while(p!=st->bottom)
{
cout<<p->value<<" ";
p=p->lastIn;
}
cout<<endl;
}

void main()
{
int len=10;
LinkStack* st = createLinkStack();
int v;
for(int i=0;i<len;i++)
{
v = rand() % 100;
cout<<v<<" ";
push(st,v);

}
cout<<endl;
outPut(st);
clearStack(st);

for(int i=0;i<len;i++)
{
v = rand() % 100;
cout<<v<<" ";
push(st,v);

}
cout<<endl;
outPut(st);

pop(st,&v);
cout<<v<<endl;
outPut(st);

top(st,&v);
cout<<v<<endl;
outPut(st);

pop(st,&v);
cout<<v<<endl;
outPut(st);

pop(st,&v);
cout<<v<<endl;
outPut(st);

for(int i=0;i<5;i++)
{
v = rand() % 100;
cout<<v<<" ";
push(st,v);

}
cout<<endl;
outPut(st);
if(!top(st,&v))
cout<<"fail"<<endl;
else outPut(st);

clearStack(st);

if(!top(st,&v))
cout<<"fail"<<endl;
else outPut(st);

if(!top(st,&v))
cout<<"fail"<<endl;
else outPut(st);

cin>>len;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: