zoukankan      html  css  js  c++  java
  • [LeetCode题解]206. 反转链表 | 迭代 + 递归

    方法一:迭代

    解题思路

    遍历过程,同时反转,这里需要一个指针 pre 要保存前一个节点。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            ListNode cur = head, pre = null;
            while(cur != null) {
                // 反转
                var nextTmp = cur.next;
                cur.next = pre;
                pre = cur;
    
                cur = nextTmp;  // 继续遍历下一节点
            }
    
            return pre;
        }
    }
    

    复杂度分析

    • 时间复杂度:(O(n)),其中 (n) 为链表长度。
    • 空间复杂度:(O(1))

    方法二:递归

    解题思路

    递归最重要的是定义函数的功能,本题的 ReverseList 函数就是反转链表。

    其次是找出结束条件:

    if(head == null || head.next == null) {
        return head;
    }
    

    最后是找出递推公式,假设只有链表只有两个节点时,这两个节点的交换如下:

    head.next.next = head;
    head.next = null;
    

    对于第 n 个节点,以及其第 n+1 个节点有:

    ListNode last = ReverseList(head.next);
    head.next.next = head;
    head.next = null;
    return last;
    

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null || head.next == null) {
                return head;
            }
    
            ListNode last = ReverseList(head.next);
            head.next.next = head;
            head.next = null;
    
            return last;
        }
    }
    

    复杂度分析

    • 时间复杂度:(O(n)),其中 (n) 为链表长度。
    • 空间复杂度:(O(n)),递归调用了 (n) 次,需要额外的调用栈空间。
  • 相关阅读:
    UE4 Couldn't find target rules file for target
    ue4 源码编译 虚拟内存不足 堆限制
    Windows RawInputPluginForUE4(2)
    maven的用法
    svn出现subclipse不兼容或不存在
    cglib
    Spring中bean中scope属性的意义
    org.springframework.beans.NotWritablePropertyException: Invalid property
    sql server 中的存储过程
    如何将数据库文件.mdf导入/恢复到SQL_Server2000
  • 原文地址:https://www.cnblogs.com/liang24/p/14014566.html
Copyright © 2011-2022 走看看