2010-10-29 69 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; 
}