文章目录
方法1:迭代
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
curr = head
pre = None
while curr:
temp = curr.next
curr.next = pre
pre = curr
curr = temp
return pre
方法2:递归(巧妙)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
head.next.next = head # 巧妙!
head.next = None # 注意这一步不能漏
return new_head