我有一个任务要求我用随机变量填充堆栈并以 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;
}