Description:
Sort a linked list using insertion sort.
问题描述:
用插入排序给一条链表元素排序
解法一:
思路:
将链表元素一个一个的切下来,利用两个指针,一个排好序链表的表头指针(sortedHead),一个排好序链表的表尾指针。
插入结点时分为三种情况:
+ 待插入元素比新表表头元素小
+ 待插入元素比新表表尾大
+ 待插入元素在新表表头和新表表尾之间,这个时候就要找到比待插入元素刚好大的最近结点
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head ==null || head.next == null)
return head;
ListNode sortedHead = head, sortedTail = head;
head = head.next;
sortedHead.next = null;
while(head != null){
ListNode temp = head;
head = head.next;
temp.next = null;
//new val is less than the head , just insert in the front
if( temp.val <= sortedHead.val){
temp.next = sortedHead;
sortedTail = (sortedHead == null) ? sortedHead : sortedTail;
sortedHead = temp;
}
//new val is greater than the tail, just insert in the back
else if(temp.val >= sortedTail.val){
sortedTail.next = temp;
sortedTail = sortedTail.next;
}
//new val is somewhere in the middle , we will have to find its proper location
else{
ListNode current = sortedHead;
while(current.next != null && current.next.val < temp.val){
current = current.next;
}
temp.next = current.next;
current.next = temp;
}
}
return sortedHead;
}
}