147. Insertion Sort List
Aug 4, 2016
https://leetcode.com/problems/insertion-sort-list/
Thought
The idea is simple: we gradly build the sorted list the head of which is a dummyHead
. However, extra caution is needed when we traverse the original list, we need to make a copy of next
of head.next
before we insert the head into the new list since insertion will change where the head.next
point to.
How to insert a node?
Given the head
of a sorted LinkedList, how to insert the node
into proper place?
The proper slot
is the one that head.val < node.val
and head.next.val > node.val
if head.next != null
, then make123tmp = head.next; head.next = node; node.next = tmp;
If head.next == null
, then we just append to the head
: head.next = node
, however, if we add tmp = head.next
, it would hurt, tmp
simply == null
.
Solution
|
|