关于c语言顺序栈的进栈出栈展示问题,为什么没有报错了还是运行情况不对

img

img

img

img

img


C语言顺序栈问题,关于进栈出打印展示的函数使用,已经修改到没有错误了,为什么功能还是实现起来有问题

有几个错误:
(1)stacktop函数不是所有的分支都有返回值,最好用返回值来判断是否获取成功,通过参数来获取栈顶元素。
(2)Print函数中,i应该从t->top开始,并且 if(t->top != -1)应该是 if (t->top == -1)
(3)main函数中,stacktype* t这一句,t是野指针,没有初始化,initiatest(&t)是错误的。
修改后的运行结果:

img

代码:

#include <stdio.h>
#include <stdlib.h>
#define NULL 0
#define true 1
#define MAXNUM 20
#include <string.h>
#define OK 1
typedef struct
{
    int stack[MAXNUM];
    int top;
}stacktype;

stacktype s;

int initiatest(stacktype* t)
{
    t->top = -1;
    return OK;
}
int stackfull(stacktype* t)
{
    return (t->top == MAXNUM - 1);
}
int stackempty(stacktype* t)
{
    return (t->top == -1);
}

int pushs(stacktype* t, int x)
{
    if (t->top == MAXNUM - 1)
        return NULL;
    else
    {
        t->top++;
        t->stack[t->top] = x;
        return true;
    }
}

int pops(stacktype* t)
{
    if (t->top < 0)
        return NULL;
    else
    {
        t->top--;
        return t->stack[t->top + 1];
    }
}

int stacktop(stacktype* t)
{
    if (stackempty(t))
    {
        printf("stack is empty\n");
        return NULL;
    }
    else
    {
        return t->stack[t->top];
    }
}

int Print(stacktype* t)
{
    if (t->top == -1) //修改,这里是==
        return NULL;
    else
    {
        for (int i = t->top; -1 < i; i--)
            printf("%d ", t->stack[i]);
        printf("\n");
        return true;
    }
}

int main()
{
    stacktype list;
    stacktype* t = &list;  //修改,这里给t初始化
    int x;
    int n; 
    if (initiatest(t))
        printf("初始化成功\n");
    while (1)
    {
        printf("请输入要进行的操作:\n");
        printf("1.进栈\n2.出栈\n3.获取栈顶元素\n4.打印\n0.退出\n");
        scanf("%d", &x);
        if (x == 0)
            break;
        switch (x)
        {
        case 1:
            printf("请输入要进栈的元素:");
            //int n;  //不要再switch中声明变量,部分编译器中不允许
            scanf("%d", &n);
            if (pushs(t, n))
                printf("进栈成功\n");
            else
                printf("进栈失败\n");
            break;
        case 2:
            if (!stackempty(t))
            {
                n = pops(t);
                printf("元素%d出栈\n", n);
            }
            else
                printf("出栈失败\n");
            break;
        case 3:
            if (!stackempty(t))
            {
                n = stacktop(t);
                printf("栈顶元素是:%d\n", n);
            }
            else
                printf("获得栈顶元素失败\n");
            break;
        case 4:
            if (Print(t))
                printf("打印完毕\n");
            break;
        default:
            printf("您进行了误操作,请重试!\n");
            break;
        }
    }
    return 1;
}



Print函数中,为啥top 不等于-1要return NULL呢???应该等于-1才return NULL啊

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632