c - 链表和输入

标签 c pointers struct linked-list nodes

我的总体目标是能够输入字符串并将其添加到列表中。我的主要问题与 makenewnode 有关。我相当有信心 main 和我的结构是可靠的,我对搜索中的基本代码有些信心,但具体细节看起来不太好。我的问题本质上是,main 中的 print 语句有什么问题,在搜索中使用 makenewnode 两次是多余的,并且 makenewnode 实际上是否按其应有的方式工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

wc(字数统计)应该保存wrd中的单词列表,count和next中的单词数意味着在列表中前进。

struct wc {
    struct wc* next;
    char* wrd;
    int count;
};

head 是列表的开头

struct wc* head=NULL;

makenewnode 是相当不言自明的。它需要 char* s,分配内存,添加到 count(应该是列表中的单词数)并将单词添加到 wrd(应该是单词列表)

void makenewnode(char* s){
    struct wc* newnode;
    char* newword;

    newword=malloc(strlen(s)+1);
    strcpy(newword,s);
    newnode=malloc(sizeof(struct wc));
    newnode->wrd=newword;
    newnode->count=1;
    newnode->next=head;
    head=newnode;
}

搜索应该获取输入字符串并确定它是否已在列表中。 while 循环应该运行到输入字符串末尾。它将wrd(已添加到列表中的单词)与输入进行比较,如果输入已在wrd中,则将其添加到计数中并设置found=1(只是作为一个符号,1实际上并不意味着任何东西)。如果输入不在wrd中,它将使用makenewnode为输入创建一个新节点。我觉得我的 else 语句和第二个 if 语句是多余的,但我不确定。

void search(char* linebuf){
    struct wc* node;
    int found=0;

    found=0;
    node=head;
    while(node!=NULL){
        if(strcmp(node->wrd, linebuf)==0){
            node->count++;
            found=1;
            break;
        }
        else{
            makenewnode(linebuf);

        }

    if(found==0){
        makenewnode(linebuf);
    }
    }
}

main 应该获取输入字符串(最多 100 个字符)并通过搜索运行它们(通过 makenewnode 运行)。然后它应该打印单词数(count)和单词列表(wrd)k。

int main(int argc, char* argv[]){
    struct wc* node;
    char linebuf[100];

    printf("Enter Words: ");
    while(fgets(linebuf,100,stdin)!=0){
        printf("Input line: %s", linebuf);
        printf("Enter Words: ");
        search(linebuf);
    }
    /*
    I'm pretty iffy on these print statements but the rest of main is fine (I think)
    printf("%d", count);
    printf("%s", wrd);
    */
    return 0;
}

最佳答案

更改为

void search(char* linebuf){
    struct wc* node;
    int found=0;

    //found=0;
    node=head;
    while(node!=NULL){
        if(strcmp(node->wrd, linebuf)==0){
            node->count++;
            found=1;
            break;//or return ;
        }
        node = node->next;
    }
    if(found==0){
        makenewnode(linebuf);
    }
}

关于c - 链表和输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28390249/

相关文章:

c - 删除字符串后的空格(指针)

c - 从类型 'int’ 分配给类型 ‘struct' 时类型不兼容,反之亦然

c - "make clean"结果 "No rule to make target ` 干净 '"

c - DT_DIR 未定义

c++ - 将指针传递给函数并修改它

c++ - 我可以获取数组的最后一个元素的地址吗?

python - 在 struct.unpack 格式字符串中间切换字节序

c - 高级 Unix 编程 - 第 1 章 shell 代码错误

c - 并行红/黑连续过度松弛 (SOR) 实现中的一些错误

c++ - 为什么指针从函数返回之前的值