我在c中创建了一个链表来对文本文件中的单词进行排序。插入函数是在阅读一行单词和含义由:分隔的行后添加一个节点。该文件只是一个单词:含义格式的字典行。当我运行代码时,它没有打印任何内容,也没有错误消息
type here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct node
{
char word[30];
char meaning[50];
struct node *next;//링크
};
void insert(struct node **head, char *word, char *meaning)
{
struct node *new_node = (struct node*) malloc(sizeof(struct node));
strcpy(new_node->word, word);
strcpy(new_node->meaning, meaning);
new_node->next = NULL;
if (*head == NULL) //빈 리스트
{
*head = new_node;
}
else if (strcasecmp((*head)->word, word) > 0) //첫위치 삽입
{
new_node->next = *head;
*head = new_node;
}
else //보통
{
struct node *curr = *head;
while (strcmp(curr->next->word, word) < 0)
{
curr = curr->next; //탐색위치 head에서 시작, 계속 1칸씩 옮겨가며 찾기
if(curr->next==NULL) break; //if the next node is null, break, insert new_node at the end
}
//순서 제대로 찾으면 그 위치에 연결
new_node->next = curr->next;
curr->next = new_node;
}
}
void print_list(struct node * head)
{
struct node * cur=head;
while (cur->next!= NULL)
{
printf("%s : %s\n", cur->word, cur->meaning);
if(cur->next==NULL){
return;
}
cur = cur->next;
}
}
int main()
{
FILE *fp;
char line[150];
fp = fopen("randdict.txt", "r");
if (fp == NULL)
{
printf("Unable to open file.\n");
exit(1);
}
struct node *head = NULL;
while (fgets(line, 150, fp))
{
char *new_word = strtok(line, ":");
char *new_meaning = strtok(NULL, ":");
insert(&head, new_word, new_meaning);//알파벳순으로 입력
}
fclose(fp);
print_list(head);
return 0;
}
我尝试通过获取if return语句来修改print_list函数,即使在while循环中已经有了一个条件,可以帮助我跳出循环。
1条答案
按热度按时间2w2cym1i1#
我在我的网站上重新运行了你的代码,没有改变任何东西,这就像预期的那样工作了~
我得到了这样的输出:
,我认为,根据你的要求,这是正确的...
这里唯一的建议可以是
还有