我正在尝试创建一个链接列表,用于存储来自用户输入的单词,然后打印它们。 我的代码有效,但是我想修改它以在每个单词后提示用户,直到最后一个单词是"结束"。 有关如何做到这一点的任何提示? 现在,代码提示用户,用户可以输入以空格分隔的单词,直到按Enter键,然后打印链表
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct list *ptr;
typedef struct list {
char data;
ptr next;
} node;
void insert(ptr *H, char c);
void freeList(ptr *H);
void printList(ptr H);
int main() {
ptr H = NULL;
int c;
printf("enter a single word:\n");
while (((c = getchar()) != EOF) && c != '\n')
insert(&H, (char) c);
printList(H); /*print the list*/
freeList(&H); /*free the list*/
printf("\n");
prinf("Please enter a single word:\n");
return 0;
}
void insert(ptr *H, char c) {
while (*H)
H = &(*H)->next;
*H = malloc(sizeof(**H));
(*H)->data = c;
(*H)->next = NULL;
}
void freeList(ptr *H) {
while (*H) {
ptr tmp = *H;
*H = (*H)->next;
free(tmp);
}
}
void printList(ptr H) {
// NOTE: No need for a pointer-to-pointer here.
while (H) {
printf("%c", H->data);
H = H->next;
}
}
答案 0 :(得分:0)
修改后的样本
int isEndKeyword(ptr H){
const char *end_keyword = "end";
while(*end_keyword){
if(H){
if(*end_keyword++ != H->data)
return 0;//false
} else //short
return 0;
H = H->next;
}
return H == NULL;//match
}
int main() {
ptr H = NULL;
int c;
char prev = ' ';
while(1){
c = getchar();
if(isspace(c) || c == EOF){
if(!isspace(prev)){ //word is exist
if(!isEndKeyword(H)){
printList(H); /* print the word */
printf("\n");
} else {
c = EOF;
}
freeList(&H); /* free the word */
}
if(c == EOF)
break;//loop end
} else {
insert(&H, (char) c);
}
prev = c;
}
return 0;
}