鏈棧

#include <iostream>
using namespace std;

typedef int StackElemType;

typedef struct Node
{
    StackElemType data;
    struct Node *next;
}StackNode,*LinkStack; 

void InitStack(LinkStack &top);
int StackEmpty(LinkStack top);
void Push(LinkStack top,StackElemType e);
void Pop(LinkStack top,StackElemType &e);
StackElemType GetTop(LinkStack top);
void PrintStack(LinkStack top);
void InputStack(LinkStack top);


int main(int argc, char const *argv[])
{
    LinkStack stack;
    InitStack(stack);
    InputStack(stack);
	PrintStack(stack);
    int x;
    Pop(stack,x);
    cout<<"top:"<<GetTop(stack)<<endl;
    Pop(stack,x);
    cout<<"top:"<<GetTop(stack)<<endl;
    PrintStack(stack);
    return 0;
}

void InitStack(LinkStack &top)
{
    top = new StackNode;
    top->next = NULL;
}

int StackEmpty(LinkStack top)
{
    return top->next == NULL;
}

void Push(LinkStack top,StackElemType x)
{
    StackNode *s = new StackNode;
    s->data = x;
    s->next = top->next;
    top->next = s;
}

void Pop(LinkStack top,StackElemType &e)
{
    LinkStack s;
    s = top->next;
    if(s == NULL)
        cout<<"The stack is empty"<<endl;

    top->next = s->next;
    e = s->data;
    delete s;
}

void InputStack(LinkStack top)
{
    cout<<"請輸入一組元素,以-1結束:";
    int m;
    cin>>m;
    while(m!=-1)
    {
        Push(top,m);
        cin>>m;
    }
}

StackElemType GetTop(LinkStack top)
{
    if(StackEmpty(top))
        cout<<"The stack is empty!"<<endl;
        
	return top->next->data;
}

void PrintStack(LinkStack top)
{
    if(top->next == NULL)
        cout<<"The stack is empty"<<endl;
    else
    {
        while(top->next)
        {
            cout<<top->next->data<<" ";
            top = top->next;
        }
    }
    cout<<endl;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章