我有一个实现堆栈的 C 程序。
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
struct stack{
struct node *head;
struct node *data_node;
};
int push(struct stack *a_stack, int i){
a_stack->data_node = malloc(sizeof(struct node));
if(a_stack->data_node == NULL){
puts("Error: Cannot allocate sufficient memory.");
exit(1);
}
a_stack->data_node->data = i;
a_stack->data_node->link = a_stack->head;
a_stack->head= a_stack->data_node;
return 0;
}
int pop(struct stack *a_stack){
if(a_stack->head==NULL){
return '\n';
}
int temp = a_stack->head->data;
a_stack->data_node = a_stack->head;
a_stack->head = a_stack->head->link;
free(a_stack->data_node);
return temp;
}
int minimum(struct stack *a_stack){
if(a_stack->head==NULL){
return '\n';
}
int min = a_stack->head->data;
struct node *a_node = a_stack->head;
while(a_node!=NULL){
if(min>a_node->data){
min = a_node->data;
a_node = a_node->link;
}
}
return min;
}
int init_stack(struct stack *a_stack){
a_stack->head = NULL;
a_stack->data_node = NULL;
}
int handle_input(struct stack *test){
char* input_string = (char*)malloc(20);
scanf("%s", input_string);
// gets(input_string);
char* pop_cmd = "-";
char* min_cmd = "min";
int num;
if (strcmp(pop_cmd, input_string) == 0){
printf("%d\n", pop(test));
}
else{
if (input_string[0] == 'm'){
printf("%d\n", minimum(test));
}
else{
num = atoi(input_string);
push(test, num);
}
}
return 0;
}
int main(void){
int no_of_input, counter;
struct stack test;
init_stack(&test);
scanf("%d", &no_of_input);
for(counter=no_of_input; counter>0; counter=counter-1){
handle_input(&test);
};
return 0;
}
问题是如果我想输入“min”,它是计算数组最小元素的命令,程序会永远等待输入。在搜索了很长一段时间后,我仍然不知道为什么会发生这种情况。