C语言顺序栈问题,关于进栈出打印展示的函数使用,已经修改到没有错误了,为什么功能还是实现起来有问题
关于c语言顺序栈的进栈出栈展示问题,为什么没有报错了还是运行情况不对
C语言顺序栈问题,关于进栈出打印展示的函数使用,已经修改到没有错误了,为什么功能还是实现起来有问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 技术专家团-小桥流水 2022-11-28 15:41关注
有几个错误:
(1)stacktop函数不是所有的分支都有返回值,最好用返回值来判断是否获取成功,通过参数来获取栈顶元素。
(2)Print函数中,i应该从t->top开始,并且 if(t->top != -1)应该是 if (t->top == -1)
(3)main函数中,stacktype* t这一句,t是野指针,没有初始化,initiatest(&t)是错误的。
修改后的运行结果:代码:
#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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
- ¥15 机器人轨迹规划相关问题
- ¥15 word样式右侧翻页键消失