206. Reverse Linked List



206. Reverse Linked List (Easy) 反转链表

题干

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

img

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

img

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

解法

朴素解法(双指针)

第一个元素指向None,然后后续元素逐个指向前一个元素,完毕

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head
        while cur:
            next_node = cur.next
            cur.next = pre
            pre, cur = cur, next_node
        return pre

递归解法

其实还是双指针,只是换了递归的写法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        return self.reverse(None, head)

    def reverse(self, pre: Optional[ListNode], cur: Optional[ListNode]) -> Optional[ListNode]:
        if cur == None:
            return pre
        temp = cur.next
        cur.next = pre
        return self.reverse(cur, temp)