单链表反转
1.
# 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): pre = None curr = head while curr: # 先把下一个节点保存下来放到next变量中 next = curr.next # 先把当前节点的下一个节点指向pre curr.next = pre # 再把当前结点赋值给pre pre = curr # 继续下一个节点的反转 curr = next return pre if __name__ == '__main__': node = ListNode(1) node.next = ListNode(2) node.next.next = ListNode(3) node.next.next.next = ListNode(4) node.next.next.next.next = ListNode(5) s = Solution().reverseList(node)
梦想随心,天地随行