我用c做了一个链表来按顺序对文本文件中的单词进行排序。 insert 函数是在读到一行单词和意思用: 分隔后添加一个节点。该文件只是带有 word:meaning 格式的字典的几行。当我运行代码时,它没有打印任何东西,也没有错误消息
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 循环中有一个条件可以帮助我跳出循环。