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) 次,需要额外的调用栈空间。
  • 相关阅读:
    指针
    基本数据类型和string类型的转换
    golang的数据类型之基本数据类型的默认值和转换
    golang的数据类型之字符串类型
    golang的数据类型之布尔类型
    windows pyspider WEB显示框太小解决方法
    MYSQL的全局变量和会话变量
    php 日期计算 总结
    使用 PHPMailer 发送邮件
    MySQL两种表存储结构MyISAM和InnoDB的性能比较测试
  • 原文地址:https://www.cnblogs.com/liang24/p/14014566.html
Copyright © 2011-2022 走看看