Leetcode:206. 反转链表

Leetcode:206.反转链表

题目描述

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路1:迭代

使用三个指针分别指向之前,现在和将来的位置,然后遍历逆转即可

思路2:递归

需要考虑从尾指针开始,然后开始递归,即考虑从后开始。然后利用当前指针的下一个位置进行递归,然后逆转。

代码

代码1

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode pre = null;
        ListNode now = head;
        ListNode forward = head.next;

        while(now != null){
            now.next = pre;
            pre = now;
            now = forward;
            if (forward != null){
                forward = forward.next;
            }
        }
        return pre;
    }
}

代码2

class Solution2 {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode pre = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return pre;
    }
}

复杂度分析

思路1时间复杂度

$O(n)$

思路1空间复杂度

$O(1)$

思路2时间复杂度

$O(n)$

思路2空间复杂度

$O(n)$会使用n层栈空间


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:234. 回文链表 Leetcode:234. 回文链表
Leetcode:234.回文链表题目描述请判断一个链表是否为回文链表。 示例 1:输入: 1->2 输出: false 示例 2:输入: 1->2->2->1 输出: true 进阶:你能否用 O(n) 时间
2020-04-07
下一篇 
Leetcode:160. 相交链表 Leetcode:160. 相交链表
[Leetcode:160.相交链表]题目描述编写一个程序,找到两个单链表相交的起始节点。 如下面的两个链表: 在节点 c1 开始相交。 示例 1:输入:intersectVal = 8, listA = [4,1,8,4,5],
2020-04-06
  目录