對鏈表進行插入排序。
插入排序的動畫演示如上。從第一個元素開始,該鏈表可以被認為已經部分排序(用黑色表示)。
每次迭代時,從輸入數據中移除一個元素(用紅色表示),并原地將其插入到已排好序的鏈表中。
插入排序算法:
插入排序是迭代的,每次只移動一個元素,直到所有元素可以形成一個有序的輸出列表。
每次迭代中,插入排序只從輸入數據中移除一個待排序的元素,找到它在序列中適當的位置,并將其插入。
重復直到所有輸入數據插入完為止。
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
代碼
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public ListNode insertionSortList(ListNode head) {ListNode dumpy=new ListNode(Integer.MIN_VALUE);dumpy.next=head;ListNode pre=dumpy;while (head!=null)//遍歷所以節點{ListNode temp=dumpy.next,curPre=dumpy;boolean change=false;while (temp!=head)//從當頭節點到當前節點查找放置的位置{if(head.val<=temp.val)//將當前節點連到合適位置{pre.next=head.next;head.next=temp;curPre.next=head;change=true;break;}curPre=temp;temp=temp.next;} if(change)//當前節點已經變化位置的情況{head=pre.next;}else {//不需要變化位置的情況pre=head;head=head.next;}}return dumpy.next;}
}