【做题也是一场游戏】206. 反转链表

154 阅读1分钟

题目地址

leetcode-cn.com/problems/re…

题目描述

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

题解

迭代

class Solution {
    public ListNode reverseList(ListNode head) {

        ListNode current = head;
        ListNode pre = null;

        while (current != null) {
            ListNode next = current.next;
            current.next = pre;
            pre = current;
            current = next;
            
        }

        return pre;

    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),其中 nn 是链表的长度。需要遍历链表一次。
  • 空间复杂度:O(1)O(1)

递归

class Solution {
    public ListNode reverseList(ListNode head) {

        if (head == null) {
            return null;
        }

        if (head.next == null) {
            return head;
        }

        ListNode next = head.next;
        head.next = null;
        ListNode newHead = reverseList(next);
        next.next = head;

        return newHead;

    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),其中 nn 是链表的长度。需要对链表的每个节点进行反转操作。
  • 空间复杂度:O(n)O(n),其中 nn 是链表的长度。空间复杂度主要取决于递归调用的栈空间,最多为 nn 层。