我有一个任务,要求我用随机变量填充堆栈并在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;
}
Run Code Online (Sandbox Code Playgroud)
你的推动应该是
(*top)++;
stack[*top] = value;
Run Code Online (Sandbox Code Playgroud)
这是第一个递增到下一个空位置然后插入.该top变量总是指向顶部元素.因此,推,先增加然后分配.要弹出,首先在顶部提取值然后递减.
注意:上面的线可以用棍棒 stack[++(*top)] = value
在当前的代码,在第一推,你的代码stack[*top++] = item,用后增量试图将值分配给当前值的*top是-1再增加,这是不对的.
关于推送例程的这种修改,pop例程是可以的.