Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null
, return 0->1->2->3->null
.
1,使用dummy节点,便于处理插入位置为首位的问题。
2,1个head指针,指向待处理list首位。
3,1个临时变量,保存下一个head节点位置。
此题一个指针+一个临时变量即可。已排序list不需要和未排序list保持相连。
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);
while (head != null) {
ListNode node = dummy;
while (node.next != null && node.next.val < head.val) {
node = node.next;
}
ListNode temp = head.next;
head.next = node.next;
node.next = head;
head = temp;
}
return dummy.next;
}
}