链栈

来源:互联网 发布:上海磁记录数据恢复 编辑:程序博客网 时间:2024/06/05 14:40
#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;}

0 0
原创粉丝点击