我的总体目标是能够输入字符串并将其添加到列表中。我的主要问题与 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/