码迷,mamicode.com
首页 > 其他好文 > 详细

逆置单链表

时间:2015-08-04 18:56:08      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

我自己的方法是用的递归,毕竟也是接触了一点点点点点点 scheme 的骚年是吧,代码如下:

ListNode* reverseList(ListNode* head) {
    if (head == nullptr){
        return nullptr;
    }
    
    ListNode* newHead = nullptr;
    
    function<void(ListNode*)> reverse;
    reverse = [&](ListNode* node)
    {
        if (node->next == nullptr){
            newHead = node;
            return;
        }
        
        reverse(node->next);
        node->next->next = node;
        node->next = nullptr;
    };
    reverse(head);
    return newHead;
}

毕竟是递归,我琢磨着会不会迭代会快一点,于是有了如下版本:

ListNode* reverseList(ListNode* head) {
    if (head == nullptr || head->next == nullptr){
        return head;
    }
    
    ListNode* previous = head;
    ListNode* current  = head->next;
    ListNode* next     = nullptr;
    while (current != nullptr){
        next = current->next;
        current->next = previous;
        previous = current;
        current  = next;
    }
    head->next = nullptr;
    return previous;
}

 结果也是 8ms 啊,令人失望。

逆置单链表

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/4702567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!