2017-06-13 54 views
-1

任何人都可以告訴我我的代碼有什麼問題嗎?
我想創建非返回函數void在鏈表的末尾插入一個節點。遞歸地在末尾插入單鏈表c

void insert_tail_Recursively(struct node **phead, int key) { 
    if (*phead == NULL) { 
    Node*temp = malloc(sizeof(Node)); 
    temp->data = key; 
    temp->pLeft = temp->pRight = NULL; 
    *phead = temp; 
    } else { 
    Node*temp = malloc(sizeof(Node)); 
    temp->data = key; 
    temp->pLeft = temp->pRight = NULL; 

    /* data more than root node data insert at right */ 
    if ((temp->data > (*phead)->data) && ((*phead)->pRight != NULL)) 
     insert_tail_Recursively((*phead)->pRight, key); 
    else if ((temp->data > (*phead)->data) && ((*phead)->pRight == NULL)) { 
     (*phead)->pRight = temp; 

    } 

    /* data less than root node data insert at left */ 
    else if ((temp->data < (*phead)->data) && ((*phead)->pLeft != NULL)) 
     insert_tail_Recursively((*phead)->pLeft, key); 
    else if ((temp->data < (*phead)->data) && ((*phead)->pLeft == NULL)) { 
     (*phead)->pLeft = temp; 
    } 
    } 
} 
+0

這是什麼條件溫度 - >數據< (*phead)->數據是什麼意思?它與「名單的結尾」有什麼關係? –

+0

你有什麼錯誤? –

+1

您正在詢問是否添加到列表中,但代碼是關於添加到樹中的。沒有'struct node'的定義。即使在添加之後,代碼也無法正確編譯。請修正編譯錯誤,這裏有意義。 – ArturFH

回答

1

您的代碼過於複雜,導致錯誤。例如有內存泄漏。

看來你的意思是以下。

void insert_tail_Recursively(struct node **phead, int key) 
{ 
    if (*phead == NULL) 
    { 
     *phead = malloc(sizeof(struct node)); 
     (*phead)->data = key; 
     (*phead)->pLeft = (*phead)->pRight = NULL; 
    } 
    else 
    { 
     phead = key < (*phead)->data ? &(*phead)->pLeft : &(*phead)->pRight; 
     insert_tail_Recursively(phead, key); 
    } 
} 
+0

非常乾淨和簡潔的樹插入代碼,加我1從 – BlueStrat

+0

這不是一個問題嗎?您的函數將修改傳遞給它的原始根指針。 –

+0

@Coldspeed是的,當樹爲空且指針等於NULL時,它將修改根目錄。但這不是問題。這是一個解決方案。 –