问题和代码放下面了,为什么会错呀,

img


#include

#define MaxSize 100

using namespace std;

typedef int ElemType;

struct SqStack{

ElemType date[MaxSize];

int top;

};

void InitStack(SqStack* &S){

S=(SqStack*)malloc(sizeof(SqStack));//初始化栈

S->top =-1;

}

void Push(SqStack* & S,ElemType M,ElemType &e){//放 有多少个数的 M, 和 e (用来接收退栈的元素)

int date;//建立一个date 表示放入栈的元素

while(int n=0

cin>>date;//输入数据

if(date!=-1){//如果不是-1 进栈

S->top++;

S->date[S->top]=date;

}

else if(date==-1){//如果是-1

if(S->top==-1){ //判断这个时候top 虽不是-1,如果所输出错误

cout<<"ERROR" <

}

else{//如果不是-1,退栈

e=S->date[S->top];

S->top--;

}

}

n++;//n++

}

if(S->top==-1){//while 循环完之后,如果是空的输出 空

cout<<"EMPTY" <

}

}

void GetTop(SqStack*S,ElemType&e){//取栈顶元素

e=S->date[S->top];

cout<

}

int main(){

SqStack *S;

ElemType M;

ElemType e=0;

cin>>M;//设置有多少个元素

Push(S,M,e);

GetTop(S,e);

return 0;

}

img

main函数里,Push函数之前,加上InitStack(S)啊,你不初始化就用,不死才怪啊

没什么大问题,修改如下,供参考:

#include <iostream>
//#include<bits/stdc++.h>
#define MaxSize 100
using namespace std;
typedef int ElemType;

struct SqStack{
    ElemType date[MaxSize];
    int top;
};

void InitStack(SqStack* &S){

    S=(SqStack*)malloc(sizeof(SqStack));//初始化栈
    S->top =-1;
}

void Push(SqStack*& S,ElemType M,ElemType& e){//放有多少个数的 M, 和 e (用来接收退栈的元素)

    int date,n = 0;//建立一个date 表示放入栈的元素
    while(n < M){//不超过 M,代表后面有 M 个数据
        cin>>date;//输入数据
        if(date!=-1){//如果不是-1 进栈
            S->top++;
            S->date[S->top]=date;
        }
        else if(date==-1){//如果是-1
            if(S->top==-1){ //判断这个时候top 虽不是-1,如果所输出错误
                cout<<"ERROR" <<endl;
            }
            else{//如果不是-1,退栈
                e=S->date[S->top];
                S->top--;
            }
        }
        n++;//n++
    }
    if(S->top==-1){//while 循环完之后,如果是空的输出 空
        cout<<"EMPTY" <<endl;
    }
}

void GetTop(SqStack* S,ElemType& e){//取栈顶元素
    e=S->date[S->top];
    cout<<e<<endl;
}

int main(){

    SqStack *S;

    ElemType M;

    ElemType e=0;
    InitStack(S);
    cin>>M;//设置有多少个元素

    Push(S,M,e);

    GetTop(S,e);

    return 0;
}