首页 > 代码库 > 堆栈(链栈)

堆栈(链栈)

#include<cstdlib>
#include<iostream>
#include<fstream>
using namespace std;

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef char SElemType;

typedef struct StackNode{
    SElemType data;
    struct StackNode *next;
}StackNode,*LinkStack;

//链栈的初始化
Status InitStack(LinkStack &S){
    S=NULL;
    return OK;
}

//链栈的入栈
Status Push(LinkStack &S,SElemType e){
    LinkStack p;
    p=new StackNode;//生成新结点
    p->data=http://www.mamicode.com/e;//将新节点数据域置为e" 1.初始化\n ";
    cout<<" 2.入栈\n ";
    cout<<" 3.读栈顶元素\n ";
    cout<<" 4.出栈\n ";
    cout<<" 0.退出\n\n ";
    choose=-1;
    while(choose!=0){
        cout<<" 请选择: ";
        cin>>choose;
        switch(choose){
            case 1:
            if(InitStack(s)){
                flag=1;
                cout<<" 成功对栈进行初始化\n\n ";
            }else
                cout<<" 初始化栈失败\n\n ";
                break;
            case 2:{
                fstream file;
                file.open("SqStack.txt");
                if(!file){
                    cout<<" 错误 为找到文件!\n\n "<<endl;
                    flag=0;
                    exit(ERROR);
                }
                if(flag){
                    flag=1;
                    cout<<" 进栈元素依次为: \n ";
                    while(!file.eof()){
                        file>>j;
                        if(file.fail())break;
                        else{
                            Push(s,j);
                            cout<<j<<" ";
                        }
                    }
                    cout<<endl<<endl;
                }else cout <<" 栈未建立,请重新选择 \n\n ";
                file.close();
            }
            break;
            case 3:
            if(flag!=-1 && flag!=0)
                cout<<" 栈顶元素为 : \n"<<GetTop(s)<<endl<<endl;
            else cout<<" 栈中无元素,请重新选择\n" <<endl;
            break;
            case 4:
            if(flag==1){
                flag=0;
                cout<<" 依次弹出的栈顶元素为:\n ";
                while(Pop(s,t))
                    cout<<t<<" ";
                    cout<<endl<<endl;
            }else cout <<" 栈未建立,请重新选择\n\n";
            break;
                         
        }
    }
    
    return 0;
}

 

堆栈(链栈)