将文本文件读入链接列表(打印序列错误)

时间:2014-01-17 20:47:58

标签: c sorting linked-list bubble-sort

我使用bubble sort函数对链表进行排序,但是我打印的时候 它实际上并没有打印排序的列表。 你能否告诉我这个错误,以便我可以走得更远:

完整运行程序:

#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>

struct employee
{
char name[30];
char surname[30];
char address[30];
char cell[30];
struct emp *next;
}*start=NULL;

struct employee *new_node;
struct employee *current;
FILE *fp;

int main(char *argv[],int argc)
{
file_open();
printf("Before bubble sort:\n");
print_list(start);
printf("After  bubble sort:\n");
bubble_sort();
print_list(start);
return 0;
}

file_open()
{
char fname[20];
char line[128];
printf("ENTER THE FILE NAME:");
scanf("%s",fname);
fp=fopen(fname,"r");
if(fp != NULL)
{
    while(fgets(line,sizeof(line),fp) != NULL)
    {
        //printf("FILE OPEN SUCCESSFULL");
        splitline(line);
        //printf("%s",line);
    }
    fclose ( fp );
}
else
{
    printf("ERROR OPEN FILE\n");
    return (1);
}
return 0;

}

 int splitline(char str[])
 {
 new_node=(struct employee*)malloc(sizeof(struct employee));
 char *store;
 store=strtok(str,", ");
 strcpy(new_node->name,store);
 store=strtok(NULL,", ");
 strcpy(new_node->surname,store);
 store=strtok(NULL,", ");
 strcpy(new_node->address,store);
 store=strtok(NULL,", ");
 strcpy(new_node->cell,store);
 new_node->next=NULL;

 if(start == 0)
 {
 start=new_node;
 current=new_node;
 }
 else
 {
current->next=new_node;
current=new_node;
 }
//print_list(current);
 return 0;
 }

 void print_list(struct employee *start)
 {
struct employee *ptr;
ptr=start;
while(ptr!=NULL)
{
printf("%s\n%s\n%s\n%s\n",ptr->name,ptr->surname,ptr->address,ptr->cell);
ptr=ptr->next;
}
printf("\n");

}

void bubble_sort(struct employee *start)
{
struct employee *a = NULL;
struct employee *b = NULL;
struct employee *c = NULL;
struct employee *e = NULL;
struct employee *tmp = NULL;


while(e != start->next) {
c = a = start;
b = a->next;
while(a != e) {
if(a->name > b->name) {
if(a == start) {
 tmp = b -> next;
 b->next = a;
 a->next = tmp;
 start = b;
 c = b;
} else {
 tmp = b->next;
 b->next = a;
 a->next = tmp;
 c->next = b;
 c = b;
}
} else {
c = a;
a = a->next;
}
b = a->next;
if(b == e)
e = a;
}
}

}

1 个答案:

答案 0 :(得分:3)

你在每个领域都复制过相同的东西。

strcpy(new_node->name,store);
strcpy(new_node->surname,store);
strcpy(new_node->address,store);
strcpy(new_node->cell,store);

您应该对splitlinecreate_node

抱怨
int AddNodeFromLine(char str[])
{
new_node=(struct employee*)malloc(sizeof(struct employee));
new_node->next=NULL;
char *store;
store=strtok(str,", ");
strcpy(new_node->name,store);
store=strtok(NULL,", ");
strcpy(new_node->surname,store);
store=strtok(NULL,", ");
strcpy(new_node->address,store);
store=strtok(NULL,", ");
strcpy(new_node->cell,store);
new_node->next=NULL;

if(start == 0)
{
    start=new_node;
    current=new_node;
}
else
{
    current->next=new_node;
    current=new_node;
}
print_list(current);
return 0;
}
相关问题