對鏈表進行插入排序。
插入排序的動畫演示如上。從第一個元素開始,該鏈表可以被認爲已經部分排序(用黑色表示)。
每次迭代時,從輸入數據中移除一個元素(用紅色表示),並原地將其插入到已排好序的鏈表中。
插入排序算法:
- 插入排序是迭代的,每次只移動一個元素,直到所有元素可以形成一個有序的輸出列表。
- 每次迭代中,插入排序只從輸入數據中移除一個待排序的元素,找到它在序列中適當的位置,並將其插入。
- 重複直到所有輸入數據插入完爲止。
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
思路:
先將鏈表第一個元素斷開聯繫,默認一個元素是已經排好序的,在將剩餘元素標記爲未排序的鏈表,之後每次循環未排序鏈表中每一個元素, 先和排序鏈表的頭比較,如果比頭下則直接插入到頭前面,如果比頭大則依次遍歷排序數組中每一個元素,知道找到比當前元素大的元素,然後將其插入到這個元素前面,如果一直遍歷到最後都沒有比他大的則直接插入到最後。代碼如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode InsertionSortList(ListNode head) {
if(head == null || head.next == null) return head;
//未排序的鏈表,默認第一個元素是排好序的
ListNode noFinish = head.next;
head.next = null; //排好序的鏈表
ListNode current,finish; //current是未排序鏈表每一個值 finish是排好序的鏈表
while(noFinish != null){
current = noFinish;
noFinish = noFinish.next;
current.next = null; //斷開聯繫,取出當前未排序的節點
if(head.val > current.val){ //和排序鏈表中第一個元素比較
current.next = head;
head = current;
continue;
}
finish = head;
while(finish.next != null){ //和排序鏈表後面每一個元素比較
if(finish.next.val > current.val){
current.next = finish.next;
finish.next = current;
break;
}
finish = finish.next;
}
if(finish.next == null){ //直接加入到最後一個元素
finish.next = current;
}
}
return head;
}
}