
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head : return None
if not head.next: return head
pre = head
cur = head.next
pre.next = None
while cur:
nextnode = cur.next
cur.next = pre
pre = cur
cur = nextnode
return pre
看了下参考链接:【反转链表】:双指针,递归,妖魔化的双指针  可以将前面的情况合并写:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur = head
pre = None
while cur:
nextnode = cur.next
cur.next = pre
pre = cur
cur = nextnode
return pre
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next : return head
res = self.reverseList(head.next)
head.next.next = head
head.next = None
return res
根据代码写的具体过程: 
|