[英]Insertion sort debug help
以下C代码不起作用(仅清除列表):
/* Takes linkedlist of strings */
static int insertSort (linkedlist *list) {
linkedlist sorted;
void *data;
node *one, *two, *newnode;
unsigned int comp, x;
removeHeadLL (list, &data);
initLL (&sorted);
addHeadLL (&sorted, data);
while (list->count) {
removeHeadLL (list, &data);
two = sorted.head;
x = 0;
for (comp = strcomp (data, two->data) ; comp > 1 && x < sorted.count ; x++) {
one = two;
two = two->next;
}
if (x) {
newnode = malloc (sizeof(node));
newnode->next = two;
newnode->data = data;
one->next = newnode;
}
else {
addHeadLL(&sorted, data);
}
(sorted.count)++;
}
destroythis (list);
list = &sorted;
return 0;
}
如果您的意图是真正修改输入指针list
以指向此函数内部分配的内存,则需要将该函数声明为
static int insertSort (linkedlist **list)
然后返回sorted
后的新建列表,如下所示:
*list = &sorted;
就目前而言,对destroylist
的调用释放了条目中list
内容,但分配仅修改了输入指针的本地副本 。
换句话说,在您的原始代码中此行:
list = &sorted;
在函数外的效果完全为零,但此行:
destroythis (list);
确实释放了条目list
所拥有的内存。 因此,返回后,您的输入指针现在将访问一个空列表。
危险,威尔·罗宾逊:未经测试的代码。
struct list { char *datum; struct list *next; };
typedef struct list *listptr;
listptr insert(char *x, listptr xs) {
listptr result = xs;
listptr *from = &result;
listptr new = (listptr) malloc(sizeof(struct list));
while (xs != null && strcmp(xs.datum, x) < 0) {
from = &xs;
xs = xs->next;
}
new.datum = x;
new.next = xs;
*from = new;
return result;
}
listptr isort(listptr xs) {
listptr result = null;
for(; xs != null; xs = xs->next) {
insert(xs.datum, result);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.