算法与数据结构之顺序栈的基本操作(语言 c++)


#include<iostream>
#include<stdlib.h>
using namespace std;

#define MAXSIZE  100
typedef int Status;
typedef int SElemType;

typedef struct {
    SElemType *base;
    SElemType *top;
    int stacksize;
} SqStack;

Status InitStack(SqStack &S) {
    S.base = new SElemType[MAXSIZE];
    if (!S.base)
        exit(-2);
    S.top = S.base;
    S.stacksize = MAXSIZE;
    return 1;
}

Status push(SqStack &S)
 {
     int e;
    cin>>e; 
    if (S.top - S.base == S.stacksize)
        return 0; 
    *(S.top++)=e; 
    return 1;
}

Status pop(SqStack &S) 
{
    int e;
    if (S.base == S.top)
        cout<<"error";
    e=*(--S.top);
    cout<<e<<" ";
    return 1;
}

int main() {
    SqStack s;
    int n;
    int flag=1;
    InitStack(s);
    while(flag)
    {
        cin >> n;
        switch(n)
        {
            case 1:
                push(s);
                break;
            case 0:
                pop(s);
                break;
            default:
                flag=0;
                break;
        }
    }
    return 0;
}

img

img

img


图一是问题的基本描述。图二是我在oj平台上运行的错误结果。图三是内存错误,看不懂。我找到了一个错误,就是当我的栈为空的时候继续出栈,会出现随机数,但我百度了之后还是不明白要怎么防止下溢。其实我知道,出栈那行判空输出“error”其实是有问题的,所以才会输出错误,但我完全没有思路要怎么改。

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

if (S.base == S.top)
cout<<"error";
->
if (S.top - S.base == -1)
cout<<"error";
空栈不应该返回error

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^