我的一般目标是能够输入字符串并将其添加到列表中。我的主要问题是makenewnode。我非常有信心,主要和我的结构是坚实的,我对搜索的基本代码有点自信,但具体看起来不太好。我的问题基本上是,main中的print语句有什么问题,在make冗余中使用makenewnode两次,而makenewnode实际上是如何工作的。链接列表和输入
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
WC(字数)应该持有WRD单词列表,在计数的单词和未来的数是指通过列表来推进。
struct wc {
struct wc* next;
char* wrd;
int count;
};
头,就是要在列表
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中,它将添加到计数并将找到的值设置为1(就像一个符号,1实际上并不代表什么意思)。如果输入不在wrd中,它将使用makenewnode为输入创建一个新节点。我觉得我的陈述很重要,第二个陈述是多余的,但我不确定。
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);
}
}
}
主要应该接受输入字符串(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;
}
你真的有问题吗? – 2015-02-08 03:30:40
如果它有一个实际的**问题,将是一个很好的帖子** – 2015-02-08 03:31:47
对于iffy部分,使用'%s'而不是'%c'作为后者期望的单个字符 – 2015-02-08 03:33:32