[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\) 次,需要额外的调用栈空间。
posted @ 2020-11-21 09:13  大杂草  阅读(204)  评论(0编辑  收藏  举报