链接列表和输入

时间:2015-02-08 03:28:42

标签: c pointers struct linked-list nodes

我的一般目标是能够输入一个字符串并将其添加到列表中。我的主要问题是使用makenewnode。我相信主要和我的结构是可靠的,我对搜索中的基本代码有点自信,但细节看起来并不好。我的问题基本上是,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,分配内存,添加计数(应该是列表中的单词数)并将单词添加到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为输入创建新节点。我觉得我的其他陈述和第二个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运行)。然后它应该打印单词数(计数)和单词列表(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;
}

2 个答案:

答案 0 :(得分:1)

更改为

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

答案 1 :(得分:0)

搜索应该是:

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

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

主要应该是:

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

    printf("Enter Words: ");

    while((inp=fgets(linebuf,100,stdin))!=0){
        printf("Input line: %s", inp);
        search(inp);
    }
    node=head;
    while(node!=NULL){
        printf("\nWords: %s\nCount: %d\n", node->wrd,node->count);
        node=node->next;
    }
    return 0;
}

代码的其他部分都很好。