【发布时间】:2015-06-05 00:24:38
【问题描述】:
结构体stack有一个指针'a'指向一个动态分配的数组(用来保存栈的内容),一个整数'maxSize'保存了这个数组的大小(即最大可以存储的数据个数)保存在这个数组中)和一个整数'top',它存储堆栈中顶部元素的数组索引。
在initstack函数中将top的值初始化为-1,并初始化maxSize的值。 当尝试将数据推送到完整堆栈中时,在推送函数中打印消息“堆栈已满”。 在 pop 函数中打印消息“Stack is empty”,并在尝试从空堆栈中弹出数据时返回值 -1000。
在initstack函数中将top的值初始化为-1,并初始化maxSize的值。
当尝试将数据推送到完整堆栈时,在推送函数中打印消息“堆栈已满”。
在 pop 函数中打印“堆栈为空”消息,并在尝试从空堆栈中弹出数据时返回值 -1000。
请注意,“堆栈的内容是”语句在 main 函数中。在显示函数中,如果堆栈为空,则打印“{}”。
我的代码有问题:
- 它没有获取所需数量的值。
-
其次,我无法打印元素。
#include<stdio.h> #include<stdlib.h> struct stack { int * a; int top; int maxSize; }; void initstack(struct stack * p, int maxSize); void push(struct stack * p, int item); void display(struct stack p); int pop(struct stack * p); void printMenu(); int main() { struct stack p; int data,ch, data1, m; printf("Enter the maximum size of the stack\n"); scanf("%d",&m); initstack(&p,m); do { printMenu(); printf("Enter your choice\n"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the element to be pushed\n"); scanf("%d",&data); push(&p, data); break; case 2: data1 = pop(&p); if(data1 != -1000) printf("The popped element is %d\n",data1); break; case 3: printf("The contents of the stack are"); display(p); printf("\n"); break; default: return 0; } } while(1); return 0; } void printMenu() { printf("Choice 1 : Push\n"); printf("Choice 2 : Pop\n"); printf("Choice 3 : Display\n"); printf("Any other choice : Exit\n"); } void initstack(struct stack * p, int maxSize) { p->top=-1; p->maxSize=maxSize; } void push(struct stack * p, int item) { if (p->top == p->maxSize-1) { printf("Stack is full\n"); return; } p->a = (int *)malloc(sizeof(int)); p->top++; p->a[p->top] =item; p->maxSize--; } void display(struct stack p) { struct stack *p1; p1=&p; int a[30],n=0,i; for (i = p1->top ; i >= 0; i--) { printf("\n%d", p1->a[i]); } } int pop(struct stack * p) { int num; if(p->top == -1) { printf("Stack is empty\n"); return -1000; } num = p->a[p->top]; p->top--; return num; }
【问题讨论】:
-
请将代码删除为 MCVE 并正确格式化(每个缩进级别 4 个空格)。
-
“它没有获取所需数量的值”。那就是它没有做的事情,那么它在做什么呢(例如,在 X 值之后崩溃?获取所有值但忽略它们?...?)。 “我无法打印元素”..再一次,这就是它没有做的事情,那么它在做什么呢?
-
1)
p->a=(int *)malloc(p->maxSize * sizeof(stack));应该是p->a=(int *)malloc(maxSize * sizeof(int)); -
@Olaf 元素输入和弹出。
-
@Olaf 当我给出 maxSize 3 时,它会正确输入元素,但是如果我在输入 3 个值后给出 4,它开始给我消息堆栈已满。