gpt4 book ai didi

c - 用两个指针搜索链表

转载 作者:行者123 更新时间:2023-11-30 16:35:41 24 4
gpt4 key购买 nike

我目前正在为uni编写一个任务,尝试从文件或标准输入中读取数据,对所有单词进行标记并呈现出现的单词列表和每个单词的计数。

所需输出的示例:

Good bye occurred 5 times
This occurred 3 times
Hello occurred 1 time

电流输出示例:

This
1
is
1
fun!

1
This
1
is
1
fun!

不要介意输出的格式。这是一个稍后要解决的问题。

我有一个正在运行的程序,它使用声明如下的链表:

typedef struct node
{
char word[50];
int count;
struct node * next;
}words;

链表初始化如下

words * head = NULL;
head = malloc(sizeof(words));

以及分配给列表的两个指针

words * current = head;
words * search = head;

我正在努力解决的是以下代码:

while (!feof(input_file))
{
while(current->next != NULL)
{
current = current-> next;
}

//Test-loop for tokenisation
while(fgets(buffer,512, input_file) != NULL)
{
//Declaration of char token
char* token;

//Declaration of flag
int duplicate_word = 1;
//Test for-loop
for (token = strtok(buffer, " "); token != NULL; token = strtok(NULL, " "))
{
char duplication_check_token[60];
strcpy(duplication_check_token, token);

while(search != NULL)
{
char duplication_check_search[60];
strcpy(duplication_check_search, current -> word);
if (strcmp(duplication_check_search, duplication_check_token) == 0)
{
search->count++;
duplicate_word = 0;
break;
}
search = search -> next;
}

if (duplicate_word != 0)
{
while(current->next != NULL)
{
current = current-> next;

}

current = malloc(sizeof(words));
strcpy(current -> word, token);
current -> count = 1;
current -> next = NULL;

//Test print
printf("%s\n", token);
printf("%d\n", current -> count);
}

}



}

调试时,它似乎永远不会在 while(search != NULL)循环中检查整个链表。

我的哪一部分逻辑错了?

感谢您的帮助!

最佳答案

您的循环中有一个中断条件,这可能是您没有遍历所有列表的原因。所以这意味着您的列表中有重复的内容。

在循环之前添加以下内容:

int a = 0;

然后在循环中添加注释行:

++a; // before the if.
if (strcmp(duplication_check_search, duplication_check_token) == 0)
{
search->count++;
duplicate_word = 0;
printf("%d\n", a); // to check what was the index of the item causing the break
getchar(); // pause until next keypress
break;
}

关于c - 用两个指针搜索链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com