2012-06-14 53 views
4

我需要遞歸複製兩個鏈接列表並返回新的list。我需要複製它們的方式是list1中的一個元素,一個來自list2。如果一個列表比另一個短,則只需附加較長列表的其餘元素。通過混合項目遞歸複製兩個鏈接列表

例輸入:list1 = [1,2,3], list2 = [4,5,6,7]; result = [1,4,2,5,3,6,7];

這裏是我的缺陷(現在是正確的)代碼:

node *copy(node *list1, node *list2) 
{ 
    if (list1 == NULL && list2 == NULL) return NULL; 

    else if (list1 != NULL && list2 != NULL) { 
     node *result; 
     result = newnode(); 

     result->data = list1->data; 
     result->next = newnode(); 
     result->next->data = list2->data; 

     result->next->next = copy(list1->next, list2->next); 

     return result; 
    } 
    else if (list1 != NULL && list2 == NULL) { 
     node *result; 
     result = newnode(); 

     result->data = list1->data; 
     result->next = copy(list1->next, NULL); 

       return result; 
    } 
    else if (list1 == NULL && list2 != NULL) { 
     node *result; 
     result = newnode(); 

     result->data = list2->data; 
     result->next = copy(NULL, list2->next); 

       return result; 
    }   
} 

有人能指出我正在做的錯誤?

編輯:現在它的工作。我錯過了兩個返回語句。

+0

它必須是遞歸的嗎?不能是一個簡單的叔叔,像一個for? –

回答

2

如果分支的話,你似乎缺少底部兩個返回語句。

0

你可以把它全部在一個循環中減少的塊數:

node *copy_two_interlaced(node *list1, node *list2) 
{ 
    node *result=NULL, **pp = &result; 

    while (list1 || list2) { 
     if (list1) { 
     *pp = newnode(); 

     (*pp)->data = list1->data; 
     (*pp)->next = NULL; 
     list1 = list1->next; 
     pp = &(*pp)->next; 
     } 
     if (list2) { 
     *pp = newnode(); 

     (*pp)->data = list2->data; 
     (*pp)->next = NULL; 
     list2 = list2->next; 
     pp = &(*pp)->next; 
     } 
    } 
    return result; 
} 

哦,對不起,這不是遞歸。這是一個(非常難看的)遞歸版本:

node *copy_two_interlaced_recursive(node *list1, node *list2) 
{ 
    node *result=NULL; 

     if (list1) { 
     result = newnode(); 
     result->data = list1->data; 
     result->next = copy_two_interlaced(list2, list1->next); 
     return result; 
     } 
     if (list2) { 
     result = copy_two_interlaced(list2, NULL); 
     } 
    } 
    return result; 
}