2013-10-23 27 views
1

我對C編程非常陌生(因此我正在研究這個愚蠢的練習)。我試圖在這個other solution看到類似的問題,但它似乎像我的編碼策略是不同的,最終我想了解我的代碼有什麼問題。我將非常感謝您的意見。插入到鏈接列表的開頭(重新訪問)

我有一個鏈表,一個函數在我的列表的開始處插入一個新節點,一個打印我的鏈表和函數的函數。

不幸的是,我對C的瞭解還不足以理解爲什麼我的函數沒有插入列表的開頭。更不幸的是,這段代碼不會崩潰。

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

typedef struct Node { 
    int data; 
    struct Node* next; 
} *Node_t; 

void print_list(Node_t root) { 
    while (root) { 
     printf("%d ", root->data); 
     root = root->next; 
    } 
    printf("\n"); 
} 

void add_to_list(Node_t *list, Node_t temp){ 
    // check if list is empty 
    if ((*list)->next == NULL) { 
     // insert first element 
     (*list) = temp; 
    } 
    else { 
     temp->next = (*list); 
     (*list) = temp; 
    } 
} 

int main() { 

    int val1 = 4; 
    int val2 = 8; 
    int val3 = 15; 

    Node_t list = malloc(sizeof(struct Node)); 
    Node_t temp1 = malloc(sizeof(struct Node)); 
    Node_t temp2 = malloc(sizeof(struct Node)); 
    Node_t temp3 = malloc(sizeof(struct Node)); 

    temp1->data = val1; 
    temp1->next = NULL; 
    temp2->data = val2; 
    temp2->next = NULL; 
    temp3->data = val3; 
    temp3->next = NULL; 

    //Initialize list with some values 
    list->data = 0; 
    list->next = NULL; 

    /* add values to list */ 
    add_to_list(&list,temp1); 
    add_to_list(&list,temp2); 
    add_to_list(&list,temp3); 

    print_list(list); 

} 

此代碼將只打印我試圖添加到列表中的最後一個節點,因此將覆蓋以前的節點。

例如:

Running… 
15 

Debugger stopped. 
Program exited with status value:0. 

回答

1

add_to_list()功能的一個錯誤:

if ((*list)->next == NULL) { // checks next of first is NULL not list is NULL 
// to insert at first 

應該只是:

if ((*list) == NULL){ // You need to check list is NULL 

檢查working code


爲什麼你只得到15最後一個節點(temp3)的值?

因爲在主你創建三個臨時節點初始化未來每一個節點的爲NULL,包括list節點,以便在add_to_list()功能,如果條件((*list)->next == NULL)始終判斷爲真,並list始終與溫度節點初始化。