以下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;
}
答案 0 :(得分:2)
如果您的意图是真的要修改输入指针list
以指向此函数内分配的内存,那么您需要将该函数声明为
static int insertSort (linkedlist **list)
然后从sorted
返回新建的列表,如下所示:
*list = &sorted;
按照目前的情况,对destroylist
的调用释放了list
条目中的内容,但该分配仅修改输入指针的本地副本。
换句话说,在原始代码中这一行:
list = &sorted;
在函数外部的效果完全为零,但是这一行:
destroythis (list);
确实释放了list
在进入时拥有的内存。因此,在返回之后,您的输入指针现在将访问一个空列表。
答案 1 :(得分:1)
Danger,Will Robinson:未经测试的代码。
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;
}