在堆栈中使用“push”和“pop”

我有一个任务要求我用随机变量填充堆栈并以FILO顺序弹出它们。 虽然我设法让它填满堆栈,但它似乎突然出现了最后一个元素而没有其他任何东西。 我不知道为什么。 任何帮助,将不胜感激。

#include  #include  #include  #define STACK_SIZE 10 #define STACK_EMPTY -1 void push(char [], // input/ouput - the stack char, // input - data being pushed onto the stack int *, // input/output - pointer to the index of the top of stack int); // constant - maximum size of stack char // output - data being popped out from the stack pop(char [], // input/output - the stack int *); // input/output - pointer to the index of the top of stack void push(char stack[],char item,int *top,int max_size){ stack[*top++] =item; } char pop(char stack[],int *top){ return stack[*top--]; } int main(){ char s[STACK_SIZE]; int s_top = STACK_EMPTY; // Pointer points to the index of the top of the stack char randChar = ' '; int i = 0; int j=0; int randNum = 0; srand(time(NULL)); for (i = 0; i 0; j--){ printf("Random chars:%c\n", pop(s, &s_top)); } return 0; } 

你的推动应该是

 (*top)++; stack[*top] = value; 

这是第一个递增到下一个空位置然后插入。 top变量始终指向顶部元素。 因此,推,先增加然后分配。 要弹出,首先在顶部提取值然后递减。

注意:上面的行可以用棍棒来stack[++(*top)] = value

在当前的代码中,在第一次推送时 ,你的代码stack[*top++] = item ,post增量尝试将值赋给当前值*top ,这是-1然后递增,这是错误的。

关于推送例程的这种修改,弹出例程是可以的。

我将两个答案混合在一起(一个刚刚被删除):

你必须修复pushpop

 void push(char stack[],char item,int *top,int max_size){ stack[++(*top)] = item; } char pop(char stack[],int *top){ return stack[(*top)--]; } 

现在将给出预期的结果

只看到推更新 , 推送和弹出都更新

Postfix ++--具有比一元*更高的优先级,所以为了增加top 指向的东西,你需要写(*top)++(*top)-- ; *top++将推进指针,这不是你想要的。

其次,堆栈指针应始终指向添加到堆栈的最后一个东西,因此您希望写入堆栈之前递增堆栈指针:

 stack[++(*top)] = value; 

前缀++与一元*具有相同的优先级,因此在这种情况下,括号不是严格必需的; 这些操作是从左到右应用的,因此++*top被解释为++(*top) ,但是parens有助于清楚地表达。

推和弹应始终是彼此相反的; 如果你用++(*top)推,你需要弹出(*top)--