我有一个作业要求我用随机变量填充堆栈并按 FILO 顺序将它们弹出。虽然我设法让它填满堆栈,但它似乎弹出了最后一个元素,而没有弹出任何其他元素。我不知道为什么。任何帮助,将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#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 < STACK_SIZE; i++){
randNum = 33 + (int)(rand() % ((126-33)+ 1 ));
randChar = (char) randNum;
push(s,randChar, &s_top, STACK_SIZE);
printf ("Random char: %c\n", randChar);
}
printf("-----------\n");
for(j=STACK_SIZE; j>0; j--){
printf("Random chars:%c\n", pop(s, &s_top));
}
return 0;
}
你的推动应该是
(*top)++;
stack[*top] = value;
即先递增到下一个空位置,然后再插入。这top
变量始终指向顶部元素。因此,要压入,先递增,然后分配。要弹出,首先提取顶部的值,然后递减。
注意:上面的行可以合并到stack[++(*top)] = value
在当前代码中,在第一推,你的代码stack[*top++] = item
,后增量尝试将该值分配给当前值*top
这是-1
然后递增,这是错误的。
对于推送例程的这种修改,弹出例程是可以的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)