给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
链表是有方向性的,只要改变了方向,就能做到反转。
cur:表示当前结点。
pre:表示上一个结点。
tmp:用来保存下一个结点防止链表断裂。
在操作时,先保存,再改变指向,最后赋值即可。
python3代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre, cur = None, head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
