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;
    }
  • 相关阅读:
    poj 2362 Square
    poj 1011 Sticks
    hust 1062 Divisibility
    hdu 4115 Eliminate the Conflict
    Android
    android stdio 快捷键
    Android Lint的使用
    Android studio导出配置
    fragment显示 Binary XML file line #12: Error inflating class fragment 错误
    markdown 字体颜色
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4702567.html
Copyright © 2011-2022 走看看