天天看点

Sort a linked list using insertion sort.

插入排序:每一趟将一个待排序的记录,按照其关键字的大小插入到有序队列的合适位置里,知道全部插入完成。 

在讲解直接插入排序之前,先让我们脑补一下我们打牌的过程。

先拿一张5在手里,

再摸到一张4,比5小,插到5前面,

摸到一张6,嗯,比5大,插到5后面,

摸到一张8,比6大,插到6后面,

以上的过程,其实就是典型的直接插入排序,每次将一个新数据插入到有序队列中的合适位置里。

public

class

Solution {

public

ListNode insertionSortList(ListNode head) {

if

(head == 

null

){

return

null

;

}

ListNode curNode = head.next;

ListNode pNode = 

new

ListNode(

);

pNode.next = head;

head.next = 

null

;

while

(curNode != 

null

){

ListNode compareNode = pNode;

while

(compareNode != 

null

){

if

(compareNode.next == 

null

|| compareNode.next.val>= curNode.val){

break

;

}

compareNode = compareNode.next;

}

ListNode temp = curNode.next;

curNode.next = compareNode.next;

compareNode.next = curNode;

curNode = temp;

}

return

pNode.next;

}

}