题目
Given the head of a singly linked list, reverse the list, and return the reversed list.
解题思路
递归和非递归两种方法
代码
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
while cur:
t = cur.next
cur.next = pre
pre = cur
cur = t
return pre