顺序栈实现中遇到的问题


#include
using namespace std;
#define maxsize 100

struct mystack
{
    int * top;
    int * base;
    int size;
};

struct mystack*createstack()
{
    struct mystack* newstack = new mystack[100];
    newstack->top = newstack->base;
    newstack->size = maxsize;
    return newstack;
}
bool empty(struct mystack*newstack)
{
    if (newstack->base = newstack->top)
    {
        cout << "该栈为空" << endl;
        return 1;
    }
    else
        return 0;
}
bool full(struct mystack* newstack)
{
    if (newstack->top - newstack->base == newstack->size)
    {
        cout << "该栈为满" << endl;
        return 1;
    }
    else
        return 0;
}
void push(struct mystack* newstack,int e)
{
    if(full(newstack))
    { 
        return;
    }
    *(newstack->top)= e;
    newstack->top++;
}
int pop(struct mystack* newstack)
{
    int e;
    if (empty(newstack))
    {
        return 0;
    }
    newstack->top--;
    e = *(newstack->top);
    return e;
}


int main()
{
    struct mystack* newstack = createstack();
    push(newstack, 1);
    push(newstack, 2);
    push(newstack, 3);
    while (!empty(newstack))
    {
        cout<newstack)<<' ';
    }
}

img


这个要怎么改啊

nide代码存在以下几个问题:

1.结构体指针newstack只申请了一个元素的空间,而不是100个元素的空间。应该将“struct mystack* newstack = new mystack[100];”改为“struct mystack* newstack = new mystack();”。

2.在empty函数中,进行if判断时,应该用==而不是=,因为=是赋值符号,会改变变量的值。

3.在empty和full函数中,如果栈为空或者为满,函数应该直接返回true,而不是返回1。

4.在pop函数中,如果栈为空,应该输出提示信息并且直接返回0,而不是返回e。

修改后的代码:

#include<iostream>
using namespace std;
#define maxsize 100
 
struct mystack
{
    int * top;
    int * base;
    int size;
};
 
struct mystack* createstack()
{
    struct mystack* newstack = new mystack();
    newstack->top = newstack->base;
    newstack->size = maxsize;
    return newstack;
}
 
bool empty(struct mystack* newstack)
{
    if (newstack->base == newstack->top)
    {
        cout << "该栈为空" << endl;
        return true;
    }
    else
        return false;
}
 
bool full(struct mystack* newstack)
{
    if (newstack->top - newstack->base == newstack->size)
    {
        cout << "该栈为满" << endl;
        return true;
    }
    else
        return false;
}
 
void push(struct mystack* newstack, int e)
{
    if (full(newstack))
    {
        return;
    }
    *(newstack->top) = e;
    newstack->top++;
}
 
int pop(struct mystack* newstack)
{
    if (empty(newstack))
    {
        cout << "该栈为空" << endl;
        return 0;
    }
    newstack->top--;
    int e = *(newstack->top);
    return e;
}
 
int main()
{
    struct mystack* newstack = createstack();
    push(newstack, 1);
    push(newstack, 2);
    push(newstack, 3);
    while (!empty(newstack))
    {
        cout << pop(newstack) << ' ';
    }
    cout << endl;
    return 0;
}


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

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