反转链表递归解-C

时间:2014-04-29 12:12:05

标签: c recursion linked-list reverse

我想在C中编写一个函数来通过递归反转链表,但是我看到很多方法作为迭代方式(与我一起完成)..但是以递归方式,函数总是返回0

撤消链接列表代码

node * r_reverseItem(node * head) {    
    if (head == NULL) //only one elem
        return NULL;

    node * currentNode = head;

    if(currentNode->next == NULL) { 
        //set HEAD to current TAIL since we are reversing list
        head = currentNode; 
        return head; //since this is the base case
    }

    r_reverseItem(currentNode->next);
    currentNode->next->next = currentNode;
    currentNode->next = NULL; //set "old" next pointer to NULL
}

那么,请问这个代码中的问题是什么?但是,任何有用的例子或网站也是可取的。

编辑

只是我知道我的错在哪里。我忘了添加一个返回声明(杀手错误)。所以正确的功能如下:

   node * r_reverseItem(node * head) {    
    if (head == NULL) //only one elem
        return NULL;

    node * currentNode = head;

    if(currentNode->next == NULL) { 
        //set HEAD to current TAIL since we are reversing list
        head = currentNode; 
        return head; //since this is the base case
    }

       node * newNode =r_reverseItem(currentNode->next);
           currentNode->next->next = currentNode;
           currentNode->next = NULL; //set "old" next pointer to NULL
           return newNode;
}

2 个答案:

答案 0 :(得分:2)

原始解决方案implemented in Java,我只使用您的变量名称

将其翻译为C
node* r_reverseItem(node * head)
{
    if( !head )   // empty list
        return NULL;

    if( !(head->next) ) //last element becomes the head of the reversed list
        return head;

    node *currentNode = head->next; //preserve next element
    head->next = NULL;

        node* newHead = r_reverseItem(currentNode);

    currentNode->next = head; 
    return newHead; //once you have head you don't change it 
}

答案 1 :(得分:1)

检查这个网站,基本上它解释了一个反向链接列表的三种方式,在你阅读它们之后你可以按照你想要的方式递归它

http://www.codeproject.com/Articles/27742/How-To-Reverse-a-Linked-List-Different-Ways