【发布时间】:2017-01-27 16:35:53
【问题描述】:
我想在链表上实现快速排序,但我在从文本文件读取到链表和打印所有节点时遇到问题。我只将最后一个元素打印为输出。我做错了什么?
我的文本文件如下所示(密码及其使用频率):
asdfgh 31554
snoopy1 15637
qwertyuiop 24372
soccer 21208
.
.
这是我的结构
struct list_element {
char *password;
int count;
list_element* next;
};
struct list {
list_element* first;
list_element* last;
};
ReadfromData()
void read_data(char* filename, list* mylist)
{
FILE *fp;
char password[128];
int freq;
fp = fopen(filename, "r");
if(fp == NULL)
{
perror("Error opening file");
return;
}
while(fgets(password, sizeof(password), fp))
{
list_element *node = malloc(sizeof(list_element));
char *token;
token = strtok(password, " ");
node->password = strdup(token);
if( token != NULL ){
token = strtok(NULL, " ");
}
freq = atoi(token);
node->count = freq;
node->next = NULL;
insert_list(node, mylist);
}
fclose(fp);
}
在列表中插入infront
void insert_list(list_element* le, list* mylist)
if((mylist->first = NULL)){
mylist->first = le;
}else{
le->next = mylist->first;
mylist->first = le;
}
打印列表
void print_list(list* mylist)
list_element *temp;
temp = mylist->first;
while(temp != NULL)
{
printf("pass %s and count %d \n", temp->password, temp->count);
temp = temp->next;
}
我还写了一个小函数,我在程序的开头调用它来详细化列表:
void init_list(list* mylist){
mylist = (list*)malloc(sizeof(list));
mylist->first = mylist->last = NULL;
}
但我认为在这里做 malloc 也没有意义,因为我已经一个一个地创建了节点,对吧?有点困惑。
任何建议都会很棒!
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
注意:
node->password = strdup(token); if( token != NULL ){不清楚。如果token == NULL,strdup(NULL)是problem
标签: c linked-list