Description
Sort a linked list using insertion sort.
Example
Given1->3->2->0->null
, return0->1->2->3->null
.
Solution
注意把cur node插到前面去以后,把之前的cur.prev指到cur.next
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
// write your code here
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy.next;
ListNode cur = dummy.next.next;
while (cur != null) {
ListNode next = cur.next;
if (prev.val > cur.val) {
insert(dummy, cur);
} else {
prev = cur;
}
prev.next = next;
cur = next;
}
return dummy.next;
}
private void insert(ListNode dummy, ListNode cur) {
ListNode prev = dummy;
while (prev.next != null && prev.next.val <= cur.val) {
prev = prev.next;
}
ListNode next = prev.next;
prev.next = cur;
cur.next = next;
}
}