按字母顺序对C中的链表进行排序的问题

问题描述 投票:1回答:1

我正在尝试按字母顺序对C中的链接列表进行排序。我使用的链接列表如下:

struct lineList{ //structure with all the line of the input file
    char *line;
    struct lineList *next;
};
typedef struct lineList llist;

我将从该文件中获取的某些路径保存到字符串line中:

/home/user/Scrivania/find/try
/home/user/Scrivania/find/try1
/home/user/Scrivania/tryDir

然后我尝试用这部分代码按字母顺序对它们进行排序:

char *line;
size_t len = 0;
ssize_t line_size;

llist *lHead = NULL;
llist *lTail = NULL;

FILE *fInput;

fInput = fopen(inputFile, "r"); //the file that contains the path of the file in which search.

if(fInput == NULL){
    fprintf(stderr, "Cannot open %s, exiting. . .\n", inputFile);
    exit(1);
}

while((line_size = getline(&line, &len, fInput)) != -1){
    //saving into the lineList structure
    llist *l = malloc (sizeof(llist));
    l->line = line;
    l->next = NULL;
    //sort alphabetically
    if(lHead == NULL || strcmp(l->line, lHead->line) < 0){
        l->next = lHead;
        lHead = l;
    } else {
        lTail = lHead;
        while((lTail->next != NULL) && (strcmp(l->line, lTail->next->line) >= 0)){
            lTail = lTail->next;
        }
        l->next = lTail->next;
        lTail->next = l;
    }
}
fclose(fInput);

在变量inputFile中存储了上面显示的文件的路径。如果我尝试遍历列表并打印出line的内容,我总是会得到文件的最后路径:

/home/user/Scrivania/tryDir
/home/user/Scrivania/tryDir
/home/user/Scrivania/tryDir

我的代码怎么了?

c linux sorting struct linked-list
1个回答
1
投票

字符串处理存在一些问题。为了解决这个问题,我以这种方式更改了线路分配:

 llist *l = malloc (sizeof(llist));
l->line = (char*)malloc((strlen(line)+1)*sizeof(char));
strcpy(l->line,line);
l->next = NULL;

排序正确,字符串分配是问题。


-1
投票

您可以使用标准库中的qsort

以下是如何使用它的示例。

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

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

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int main () {
   int n;

   printf("Before sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("\nAfter sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {   
      printf("%d ", values[n]);
   }

   return(0);
}
© www.soinside.com 2019 - 2024. All rights reserved.