链表反转python
def reverse_node_list(head):
if not head or not head.next:
return head
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
设置三个指针, prev指向前一个节点, head 指向现在的节点, curr指向下一个要去的节点
初始化:
prev空
head表头
先保留当前节点
挪动指针
当前节点反转
挪动prev