2013-09-28 30 views
0

這樣的想法是我定義爲一個結構鏈表印刷及添加元素

struct Node 
{ 
    struct Node *next; 
    struct Node *prev; 
    char value[5]; 
}; 

struct DoubleLinkedList 
{ 
    int size; 
    struct Node *head; 
    struct Node *tail; 
}; 

,我插入使用插入排序函數列表中的雙向鏈表。我將指針傳遞給我的雙鏈表作爲參數,並且通過向列表中添加新的4個字符的字符串節點(按字典排序的鏈表)來修改它。然後我打印鏈接列表並添加每個字符串節點。

印刷證明是有問題的。現在,用下面的代碼,輸出始終像(假設被插入在每一步的字符串是AAAA,BBBB,CCCC ......)

AAAA

BBBB - > BBBB

cccc - > cccc - > cccc

由於某些原因,鏈表結構正在將每個節點更改爲要插入的新字符串的值;我不知道爲什麼!而且,如果我嘗試將打印塊轉移到主功能,則會打印出亂碼。

int main() 
{ 
    struct DoubleLinkedList strings; 
    while (1) 
{ 
    sleep(1); 
    char s[5]; 
    GenerateRandomString(s,4); 
    InsertionSort(&strings, s); 
} 
    return 0; 
} 

void InsertionSort(struct DoubleLinkedList *sorted, char *randomstring) 
{ 
struct Node new; 
strcpy(new.value,randomstring); 
printf("Newvalue %s\n", new.value); 
if ((*sorted).size == 0) 
{ 
    new.next = NULL; 
    new.prev = NULL; 
    (*sorted).head = &(new); 
    (*sorted).tail = &(new); 
} 
else 
{ 
    printf("TEST %s\n", (*(*sorted).head).value); 
    struct Node *current; 
    current = (*sorted).head; 
    printf("CURRENT %s\n", (*current).value); 
    while (strcmp(randomstring,(*current).value) > 0) 
    { 
     current = (*current).next; 
     if (current = NULL) 
     { 
      break; 
     } 
    } 
    new.next = current; 
    if (current != NULL) 
    { 
     new.prev = (*current).prev; 
     if ((*current).prev != NULL) 
     { 
      (*(*current).prev).next = &(new); 
     } 
     else 
     { 
      (*sorted).head = &(new); 
     } 
     (*current).prev = &(new); 
    } 
    else 
    { 
     new.prev = (*sorted).tail; 
     (*((*sorted).tail)).next = &(new); 
     (*sorted).tail = &(new); 
    } 
} 
(*sorted).size++; 
struct Node *printing; 
printing = (*sorted).head; 
int i; 
for (i = 0; i < (*sorted).size - 1; i++) 
{ 
    printf("%s -> ", (*printing).value); 
    printing = (*printing).next; 
} 
printf("%s\n",(*printing).value); 
} 
+0

爲什麼不寫'sorted-> size'而不是'(* sorted).size'?我的意思是,這是更常見的。並且不要命名變量'new'。 – pzaenger

+0

'(*排序)。頭= &(new);' 本地自動變量的地址不能在範圍之外使用。 – BLUEPIXY

回答

0

您還沒有 strcpy的分配值內存(new.value,randomstring); 你很幸運,你的後續printf工作。

例如,您可以

new.value = strdup(randomstring); 

(不要忘記帶免費(new.value釋放內存),當您刪除節點,如果你這樣做,是因爲的strdup調用malloc)做的。

+0

真的很抱歉,在發佈問題之前,我實際上對我的程序做了一個小的編輯;我現在使用來分配內存作爲結構的一部分 – krandiash

0

呃,你沒有爲新的分配內存,所以當你退出InsertionSort的時候,節點是懸空的。

應在插入排序

new = (struct Node *)malloc(sizeof(struct Node)); 

然後調整一切使用指針(即新 - >的東西,而不是new.stuff和新的替代&新)。

主strings.size

此外,在未初始化

strings.size = 0; 

似乎失蹤。

最後一個,當你寫

if (current = NULL) 

我想你的意思

if (current == NULL) 

(在一些C的傳統,你會寫,如果(!電流))

有了這些修改,它似乎工作。