【发布时间】:2021-03-18 16:16:07
【问题描述】:
我的程序根据用户输入创建一堆字符,以星号终止。 PopAll() 可以完美地逐个弹出每个元素,但反复使用 pop() 不会。我不明白这是怎么发生的,因为 popAll() 只是在后台使用 pop()。
谁能告诉我怎么回事?
#include <stdio.h>
#include <stdlib.h>
struct NODE {
char value;
struct NODE *prev;
};
void push(char);
void pop();
void popAll();
int checkTerminator(char);
struct NODE *TOP = NULL;
int main()
{
char input;
while(checkTerminator(input) == 0){
scanf("%c", &input);
if(checkTerminator(input) == 0){
push(input);
}
}
printf("\nOutput:\n");
// Doesn't pop three elements
pop();
pop();
pop();
// Succesfully pops all elements
// popAll();
}
int checkTerminator(char value){
switch(value){
case '*':
return 1;
default:
return 0;
}
}
void push(char value){
struct NODE *CURRENT = (struct NODE*) malloc(sizeof(struct NODE));
CURRENT->value = value;
CURRENT->prev = TOP;
TOP = CURRENT;
}
void pop(){
printf("%c", TOP->value);
TOP = TOP->prev;
}
void popAll(){
while(TOP != NULL){
pop();
}
}
【问题讨论】:
标签: c char stack scanf singly-linked-list