206. Reverse Linked List

https://leetcode.com/problems/reverse-linked-list/

solution

  • 迭代

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head

        pre = None
        cur = head
        while cur is not None:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

时间复杂度:O(n) 空间复杂度:O(1)

  • 递归

时间复杂度:O(n) 空间复杂度:O(n)

follow up

92. Reverse Linked List II

24. Swap Nodes in Pairs

双向链表的反转

Last updated