堆栈(链栈)

#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=e;//将新节点数据域置为e
    p->next=S;//将新结点插入栈顶
    S=p;//修改栈顶指针为p
    return OK;
}

//链栈的出栈
Status Pop(LinkStack &S,SElemType &e){
    LinkStack p;
    if(S==NULL)return ERROR;//栈空
    e=S->data;
    p=S;
    S=S->next;//修改栈顶指针
    delete p;//释放原栈顶元素的空间
    return OK;
}
//取链栈的栈顶元素
SElemType GetTop(LinkStack S){
    if(S!=NULL)//栈非空
    return S->data;
}


int main(){
    LinkStack s;
    int choose,flag=0;
    SElemType j,t;
    cout<<" 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;
}

 

转载于:https://www.cnblogs.com/smallbrokenchildwen/p/6793469.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值