Leetcode 206. 反转链表

Leetcode 206. 反转链表_第1张图片

注意的点:

这道题三番五次地做错,总是想着交换首尾链表的位置,其实正确的做法就是从头到尾两两交换链表的指针方向即可。

解法:双指针

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast, slow = head, None
        while fast:
            temp = fast.next
            fast.next = slow
            slow = fast
            fast = temp
        return slow

你可能感兴趣的:(leetcode,链表,算法)