/**
* 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) {
// 2015-08-28 O(n^2)
// 建立新的dummy链
ListNode dummy = new ListNode(0);
// 遍历两个链表,一定是两个while循环嵌套
// 遍历未排序的链
while (head != null) {
// 从头遍历dummy链,找合适的插入位置
ListNode insertPos = dummy;
while (insertPos.next != null && insertPos.next.val < head.val) {
insertPos = insertPos.next;
}
// 找到插入位置,在insertPoc.next的位置插入head节点
ListNode temp = head.next;
head.next = insertPos.next;
insertPos.next = head;
head = temp;
}
return dummy.next;
}
}
[刷题]Insertion Sort List
最新推荐文章于 2022-03-03 17:17:17 发布