04 Jul 2024
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:

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

Input: head = [1,2] Output: [2,1]
Example 3:
Input: head = [] Output: []
Constraints:
[0, 5000].-5000 <= Node.val <= 5000Follow 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)