1. 递归
import sys
sys.setrecursionlimit(10000)
# 经测试python3解释器默认递归最大深度为3000,所以当链表长度大于3000的时候,会引发RecursionError异常
class Solution:
def ReverseList(self , head: ListNode) -> ListNode:
# write code here
if head is None or head.next is None:
return head
next_ = head.next
reverse = self.ReverseList(next_)
next_.next = head
head.next = None
return reverse
2.遍历翻转
class Solution:
def ReverseList(self , head: ListNode) -> ListNode:
# write code here
new_head = None
while head:
tmp = head.next
head.next = new_head
new_head = head
head = tmp
return new_head