2013-10-22 24 views
1

我被要求編寫一個驅動函數來調用遞歸函數。我想知道我需要在驅動程序功能中做什麼。使用遞歸來反轉鏈表的問題

這個程序是反轉一個鏈表。只要

void invert_r() 
{ 
    //This is the driver function for recursive_invert 

    nodeType<Type> *p, *q; 

    q = first; 
    p = first; 
    recursive_invert(q, p); 
} 
nodeType<Type>* recursive_invert(nodeType<Type> *q, nodeType<Type> *p) 
{ 
    //Invert a linked list using recursion. 
    //DO NOT create any new node in your implementation 
    if(p -> link == NULL) 
    { 
     q -> link = p; 
     return p; 
    } 
    else 
    { 
     recursive_invert(p -> link, q) -> link = p; 
    } 
    return p; 
} 
+0

很難說,我們不能看到first'是什麼'。否則一切看起來很好。你用這個代碼得到了什麼具體問題? –

+0

@ g-makulik「first」是鏈表的第一個元素。我很困惑使用驅動函數,以及如何使用它,然後調用我的遞歸函數... –

+0

該函數的輸出是首先通過迭代方法顛倒鏈表。然後通過實現invert_r()來返回鏈表來調用遞歸函數 –

回答

0
void recursiveReverse(struct node** head_ref) 
{ 
    struct node* first; 
    struct node* rest; 

    /* empty list */ 
    if (*head_ref == NULL) 
     return; 

    /* suppose first = {1, 2, 3}, rest = {2, 3} */ 
    first = *head_ref; 
    rest = first->next; 

    /* List has only one node */ 
    if (rest == NULL) 
     return; 

    /* reverse the rest list and put the first element at the end */ 
    recursiveReverse(&rest); 
    first->next->next = first; 

    /* tricky step -- see the diagram */ 
    first->next = NULL;   

    /* fix the head pointer */ 
    *head_ref = rest;    
} 
+0

你的代碼看起來不像OP的代碼。它有不同的簽名和不同的結構成員。 –

+0

約翰它只是爲了說明目的,就像一個Algo。 –

+0

請注意,我們希望解決問題中解決*特定問題的答案。如果你有一個非常相關的選擇,你*可以*考慮添加 - 但請務必解決這個問題並首先解釋爲什麼。 –