class Solution: def insertionSortList(self, head): ans = None cur = head tmp = ListNode(0) while cur is not None: if ans is None or ans.val > cur.val: tmp.val = cur.val tmp.next = ans ans = tmp cur = cur.next continue ptr = ans while ptr.next is not None and cur.val >= ptr.next.val: ptr = ptr.next tmp.val = cur.val tmp.next = ptr.next ptr.next = tmp cur = cur.next return ans
I debugged for a few time and found that after
tmp.next = ptr.next they will point to the same object, and then
ptr.next = tmp will make tmp.next point to tmp itself. But why? How can I solve it?