链表实现栈的基本操作

初始化:

void InitStack(LinkStack &s)
{
    s = NULL;
}

进栈:

void Push(LinkStack &s,ElemType e)
{
    LinkStack p;
    p = (LinkStack)malloc(sizeof(StackNode));
    p->data = e;
    p->next = s;
    s = p;//check the TopPointer
}

出栈:

ElemType Pop(LinkStack &s,ElemType &e)//the element will be save in e to return
{
    LinkStack p;
    if(s==NULL)
    {
        return 0;
    }
    else
    {
        p = s;
        e = s->data;
        s = p->next;
        free (p);
        return 1;
    }
}

取栈顶:

ElemType GetTop(LinkStack s,ElemType &e){
    if(s==NULL)
    {
        return 0;
    }
    else{
        e = s->data;
        return 1;
    }
}
完整代码:

#include 
#include 
using namespace std;
typedef int ElemType;
typedef struct StackNode
{
    ElemType data;
    struct StackNode *next;
}StackNode,*LinkStack;
//Initialize the LinkStack
void InitStack(LinkStack &s)
{
    s = NULL;
}
//Push
void Push(LinkStack &s,ElemType e)
{
    LinkStack p;
    p = (LinkStack)malloc(sizeof(StackNode));
    p->data = e;
    p->next = s;
    s = p;//check the TopPointer
}
//Pop
ElemType Pop(LinkStack &s,ElemType &e)//the element will be save in e to return
{
    LinkStack p;
    if(s==NULL)
    {
        return 0;
    }
    else
    {
        p = s;
        e = s->data;
        s = p->next;
        free (p);
        return 1;
    }
}
void Info(){
    cout<<"1:Push"<data;
        return 1;
    }
}

//StackEmpty
ElemType StackEmpty(LinkStack s)
{
    if(s==NULL)
    {
        return 1;
    }
    else
        return 0;
}
void StackDisplay(LinkStack s){
    cout<<"此时栈的状态"<data<<" ";
        s = s->next;
    }
    cout<>StLength;
    InitStack(s);
    cout<<"请输入那些元素"<>e;
        Push(s,e);
    }
    cout<<"此时栈的状态"<data<<" ";
        s = s->next;
    }
    StackDisplay(s);
    Info();
    cin>>choose;
    while(choose)
    {
        switch(choose)
        {
            case 1:{
                cout<<"请输入您要进栈的数据"<>e;
                Push(s,e);
                StackDisplay(s);
                break;
            }
            case 2:{
                cout<<"您将要弹出一个元素的值是:"<>choose;
    }
    return 0;
}

 

你可能感兴趣的:(数据结构)