码迷,mamicode.com
首页 > 其他好文 > 详细

堆栈之链表实现

时间:2014-09-25 00:46:17      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   sp   

#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;
}

 

堆栈之链表实现

标签:style   blog   color   io   os   ar   for   div   sp   

原文地址:http://www.cnblogs.com/kbyd/p/3991741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!