原来的链表是1-2-3-4-5-null
反转后是5-4-3-2-1-null
只需要循环遍历,并且借一个temp便可以完成反转
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
tmp = cur.next # 暂存后继节点 cur.next
cur.next = pre # 修改 next 引用指向
pre = cur # pre 暂存 cur
cur = tmp # cur 访问下一节点
return pre