題意:實現鏈表的插入排序
插入排序是一種O(n^2)複雜度的算法,就是每次循環找到一個元素在當前排好的結果中相對應的位置,然後插進去,經過n次迭代之後就得到排好序的結果了。
/**
* 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 dummy = new ListNode(0);//存儲排序好的鏈表
ListNode curNode = head;
while (curNode != null) {
ListNode nextNode = curNode.next;
ListNode tmpNode = dummy;
//從排序好的鏈表的第一個節點依次和當前節點比較
//如果小於當前節點,則節點後移,繼續尋找當前節點應該插入的位置
while (tmpNode.next != null && tmpNode.next.val < curNode.val) {
tmpNode = tmpNode.next;
}
//確定節點插入位置之後,交換位置
curNode.next = tmpNode.next;
tmpNode.next = curNode;
curNode = nextNode;
}
return dummy.next;
}
}