首页 > 其他 > 详细

[LeetCode题解]206. 反转链表 | 迭代 + 递归

时间:2020-11-21 10:43:22      阅读:41      评论:0      收藏:0      [点我收藏+]

方法一:迭代

解题思路

遍历过程,同时反转,这里需要一个指针 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\) 次,需要额外的调用栈空间。

[LeetCode题解]206. 反转链表 | 迭代 + 递归

原文:https://www.cnblogs.com/liang24/p/14014566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!