2014-02-18 79 views
0

我想創建一個鏈表。每個節點將保存一個結構和一個指向下一個節點的指針。當試圖從列表中間刪除一個節點時,由於分段錯誤,程序停止。我試着用這幾種不同的方法。在迭代到我想要刪除的節點後,這裏是我嘗試使用的algorythms。從鏈表中刪除節點

1.在要刪除的節點之後,設置先前節點的「下一個」指針。

// example 
node_t *current = head; 
while(current->next != NULL) { 
    if(current->next->b.y <= 5) { 
     current->next = current->next->next; // first idea, didn't work 
    } 
    current = current->next; 
} 

這,沒有工作。所以我將它調整爲

1.創建一個指向名爲temp的節點的指針。

2.將要刪除的節點複製到temp。

3.將先前節點的'下一個'指針設置爲臨時'下一個'指針。

4.free臨時

// example 
node_t *current = head; 
while(current->next != NULL) { 
    if(current->next->b.y <= 5) { 
     node_t *temp; 
     temp = current->next; 
     current->next = temp->next; 
     free(temp); 
    } 
    current = current->next; 
} 

它仍然無法正常工作。我真的不知道什麼是錯的,因爲對我來說,它看起來非常合理。我知道我必須弄清楚我是如何初始化指針的,或者如何刪除節點。如果有人能告訴我爲什麼代碼不能正常工作,我可以修復它。

+1

你可以顯示node_t結構嗎? – Coconop

+0

如果入口處有'head == NULL'這兩個片段都有問題。此外,你不處理你需要刪除頭節點的情況(所以'head-> by <= 5'。你是否瀏覽了頁面右邊的相關問題以尋求幫助? –

+0

@JonathanLeffler I因爲某種原因,在學術界受到重創的過度曝光(和imnsho毫無價值)設計,或者它只是一個bug而已= P – WhozCraig

回答

0

正如在評論中指出的那樣,您只需檢查current是否爲空以及current->next

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node_t 
{ 
    struct node_t *next; 
    int data; 
} node_t; 

static void add_node(node_t **head, int value); 
static void free_list(node_t **head); 
static void dump_list(node_t *head); 

int main(void) 
{ 
    node_t *head = 0; 
    add_node(&head, 3); 
    add_node(&head, 6); 
    add_node(&head, 9); 
    add_node(&head, 4); 
    add_node(&head, 8); 
    add_node(&head, 2); 
    dump_list(head); 

    node_t *current = head; 
    while (current != NULL && current->next != NULL) 
    { 
     if (current->next->data <= 5) 
     { 
      current->next = current->next->next; 
     } 
     current = current->next; 
    } 
    dump_list(head); 
    free_list(&head); 
    dump_list(head); 

    return 0; 
} 

static void add_node(node_t **head, int value) 
{ 
    node_t *node = malloc(sizeof(*node)); 
    node->data = value; 
    node->next = *head; 
    *head = node; 
} 

static void dump_list(node_t *head) 
{ 
    char const *pad = ""; 
    while (head != 0) 
    { 
     printf("%s %d", pad, head->data); 
     pad = " ->"; 
     head = head->next; 
    } 
    putchar('\n'); 
} 

static void free_list(node_t **head) 
{ 
    while (*head != 0) 
    { 
     node_t *next = (*head)->next; 
     free(*head); 
     *head = next; 
    } 
} 

此墜毀,直到while循環改爲同時檢查currentcurrent->next。麻煩的是,如果你刪除最後一個節點,current被賦值爲NULL,你不能解除引用。

注意:上面的代碼不檢查從malloc()返回,但不這樣做是懶惰和壞。