#include<stdio.h>
#include<stdlib.h>
struct arraystack
{
int top;
int capacity;
int *array;
};
當我嘗試運行此程序後,將一些整數值推入堆棧,當我開始從棧中彈出一個它打印一些垃圾值,但不是我輸入的那個。我想知道我的代碼中的問題在哪裏,請幫我解決?爲什麼這個堆棧程序在使用POP時給出垃圾值?
struct arraystack *createstack(int cap)
{
struct arraystack *stack;
stack = malloc(sizeof(struct arraystack));
stack->top=-1;
cap=stack->capacity;
stack->array = malloc(sizeof(int)*stack->capacity);
return(stack);
}
int isfull (struct arraystack *stack)
{
if (stack->top==stack->capacity-1)
{
return 1;
}
else
return 0;
}
int isempty (struct arraystack *stack)
{
if(stack->top==-1)
{
return 1;
}
else
return 0;
}
void push (struct arraystack *stack, int item)
{
if (!isfull(stack))
{
stack->top++;
stack->array[stack->top] = item;
}
}
int pop (struct arraystack *stack)
{
int item;
if (isfull(stack))
{
item=stack->array[stack->top];
stack->top--;
return item;
}
else
return -1;
}
int main()
{
int choice, item;
struct arraystack *stack;
stack=createstack(4);
while(1) {
clrscr();
printf("\n 1. Push");
printf("\n 2. Pop");
printf("\n 3. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1: printf("Enter a number\n");
scanf("%d", &item);
push(stack,item);
break;
case 2:
item=pop(stack);
if (item == -1)
{
printf("stack is empty");
}
else
printf("popped value is %d", item);
break;
case 3 : exit(0);
}
}
getch();
}
1)'帽=重新建立了新>的能力;' - >'重新建立了新>容量=帽;'2)'如果(isfull(堆棧))' - >'if(!isempty(stack))' – BLUEPIXY
Thx @BLUEPIXY我很感謝你的幫助 – Asif