解题思路


https://picgo.cn-sy1.rains3.com/2024/10/9bae71caafaafc1dfb209412b5123f3a.png

实现代码


class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) return null;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy.next, cur = prev.next;
        while (cur != null) {
            prev.next = cur.next;
            cur.next = dummy.next;
            dummy.next = cur;
            cur = prev.next;
        }
        return dummy.next;
    }
}

复杂度分析


  • 时间复杂度:O(N)
  • 空间复杂度:O(1)