题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
在链表开头设置虚拟dummy节点,随迭代进行head节点逐渐后移,每次迭代都需要把head之后的数字加到dummy后(即成为链表开头的第一个数字),故设置dnext = dummy.next表示链表的第一个节点,hnext = head.next表示head后的节点,dummy.next = hnext将head后的节点移到链表开头,hnext.next = dnext完成倒序,head.next = hnext.next将head节点与dnext后面的节点连接方便下一次迭代。
dummy = ListNode(0) dummy.next = head # 将dummy节点与head节点连接 while head != None and head.next != None: dnext = dummy.next # 表示链表开头的节点(不一定是head) hnext = head.next # 表示head后的节点(需要在这单次迭代中移到开头) dummy.next = hnext # 移到开头 hnext.next = dnext head.next = hnext.next return dummy.next