2010-10-29 66 views
0

下面的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; 
} 

完全上下文:http://buu700.res.cmu.edu/CMU/15123/6/

+2

“下面的C代码不起作用:” - 啊!什么不行? – 2010-10-29 01:35:57

+0

对不起,我有点含糊,因为我有点急。结果是,我最终得到了一个空白链表 - 不知道这样做会发生什么。 – 2010-10-29 01:38:42

回答

2

如果你的目的是真正改变输入指针list指向这个函数内部分配的内存,那么你需要声明的功能

static int insertSort (linkedlist **list) 

,然后返回新建从表像sorted如此:

*list = &sorted; 

因为它的立场,调用destroylist释放了什么是list入境,b ut作业只修改输入指针的本地副本

换句话说,在你原来这行代码:

list = &sorted; 

所具有的功能外恰好为零的效果,但此行:

destroythis (list); 

确确实腾出这是所拥有的记忆通过list进入。所以在返回之后,你的输入指针现在访问一个空的列表。

1

危险,威尔·罗宾逊:未经测试的代码。

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; 
}