zoukankan      html  css  js  c++  java
  • 逆置单链表

    我自己的方法是用的递归,毕竟也是接触了一点点点点点点 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 啊,令人失望。

    然后这是在过了一周之后,我写的代码:

    ListNode* reverseList(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr){
            return head;
        }
        
        auto newHead = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return newHead;
    }
  • 相关阅读:
    XML相关资源
    【翻译】Windows下文件的命名
    显示文件的16进制编码(C++)
    函数模板的匹配
    最新的flex4.1和as3.0的帮助文档
    Flash/Flex 框架简介—PureMVC
    textfield的诡异
    灵异的bug
    互联网公司的发展都在于专注和坚持。
    python内置数据类型
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4702567.html
Copyright © 2011-2022 走看看