gpt4 book ai didi

c - 带链表的快速排序

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:46 25 4
gpt4 key购买 nike

我写下了以下程序,它使用快速排序算法对使用链表将多少整数放入命令行进行排序。我不仅收到有关混合声明的 ISO C90 错误,而且我的代码中某处存在内存泄漏,我不确定如何修复它。任何帮助将不胜感激!

#include <stdio.h>
#include "linked_list.h"
#include <stdlib.h>
#include "memcheck.h"
#include <string.h>
#include <assert.h>

node *quicksort(node *list);
int ListLength (node *list);

int main(int argc, char *argv[]) {
if (argc == 1) {
fprintf(stderr, "usage: %s [-q] number1 number2 ... \
(must enter at least one argument)\n", argv[0]);
exit(1);
}
node *list;
node *sorted_list;
int i;
int intArg = 0; /* number of integer arguments */
int print = 1;
/* if -q is found anywhere then we are going
* to change the behavior of the program so that
* it still sorts but does not print the result */
for ( i = 1 ; i < argc; i++) {
if (strcmp(argv[i], "-q") == 0) {
print = 0;
}
else {
list = create_node(atoi(argv[i]), list); /* memory allocation in the create_node function */
intArg++; }
}

if (intArg == 0) {
fprintf(stderr, "usage: %s [-q] number1 number2 ...\
(at least one of the input arguments must be an integer)\n", argv[0]);
exit(1); }
sorted_list = quicksort(list);
free_list(list);
list = sorted_list;
if (print == 1) {
print_list(list); }
print_memory_leaks();
return 0; }

/* This function sorts a linked list using the quicksort
* algorithm */
node *quicksort(node *list) {
node *less=NULL, *more=NULL, *next, *temp=NULL, *end;
node *pivot = list;
if (ListLength(list) <= 1) {
node *listCopy;
listCopy = copy_list(list);
return listCopy; }
else {
next = list->next;
list = next;
/* split into two */
temp = list;
while(temp != NULL) {
next = temp->next;
if (temp->data < pivot->data) {
temp->next = less;
less = temp;
}
else {
temp->next = more;
more = temp;
}
temp = next;
}
less = quicksort(less);
more = quicksort(more); }
/* appending the results */
if (less != NULL) {
end = less;
while (end->next != NULL) {
end = end->next;
}
pivot->next = more;
end->next = pivot;
return less; }
else {
pivot->next = more;
return pivot; } }
int ListLength (node *list) {
node *temp = list;
int i=0;
while(temp!=NULL) {
i++;
temp=temp->next; }
return i; }

最佳答案

main 中,释放一个节点,即列表的原始头部:

sorted_list = quicksort(list);
free_list(list);

但是您永远不会释放任何其他节点,尽管您复制了这些节点。所以从第一个开始保存的所有原始列表节点都漂浮在无法访问的内存中。在副本上free,但在 main 中不free,或者根本不复制(并释放 中的所有节点>main,但仅在您不再需要它们之后)。

关于c - 带链表的快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9423885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com