使用用户输入的单词创建并打印链接列表

标签 c linked-list user-input nodes

我正在尝试创建一个链接列表,该列表存储用户输入的单词,然后打印它们。 我的代码可以工作,但是我想修改它以在每个单词后提示用户,直到最后一个单词“结束”。 关于我如何做到这一点有任何提示吗? 现在代码提示用户,用户可以输入以空格分隔的单词,直到按回车键,然后打印链接列表

#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;
    }
}

最佳答案

修改示例

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;
}

关于使用用户输入的单词创建并打印链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897804/

相关文章:

将 char 数组复制到另一个 char 数组而不发生内存泄漏

C - 动态结构中的相同数据

C++链表销毁函数

c - C 中的链表堆栈

c - 如何在 C 中仅读取输入中的数字(没有字母,只有数字)?

c++ - 出于不同目的重复读取由空格(或其他分隔符)分隔的 double 列表

c - 我如何知道 C 程序的可执行文件是在前台还是后台运行?

c - 用C语言编程的整数数组中的唯一随机数

java - Java中linkedList实现的删除方法

java - 如何将多个链接列表中的读取用户输入关联起来?