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) 次,需要额外的调用栈空间。
  • 相关阅读:
    剑指Offer替换空格
    转载类的静态成员函数和静态成员变量的使用
    最长递增子序列长度LIS
    剑指Offer二维数组中的查找
    转载C语言:浮点数在内存中的表示
    7 CICD实战 持续集成71 kubernetes与cicd
    9 深入kubernetes服务调度与编排91 健康检查高可用的守护者
    项目成功的⑤大因素
    Ucos_II2.52源码中文译注
    SIP协议中的认证方式
  • 原文地址:https://www.cnblogs.com/liang24/p/14014566.html
Copyright © 2011-2022 走看看