题意:使用插入排序,将链表的值从小到大排列。
分析:Insertion Sort就是把一个一个元素往已排好序的list中插入的过程。忘记插入排序过程的同学可以看插入排序维基百科
初始时,sorted list是空,把一个元素插入sorted list中。然后,在每一次插入过程中,都是找到最合适位置进行插入。因为是链表的插入操作,需要维护pre,cur和next3个指针。
pre用来发现合适的插入位置,cur指向当前需要被插入的元素,next指向下一个需要被插入的元素。
当sorted list为空以及pre.next所指向的元素比cur指向的元素值要大时,将cur节点插入pre和pre.next之间。。否则,pre指针后移。最后返回dummyhead的next即可。
class Solution {
public static ListNode insertionSortList(ListNode head) {
if( head == null ){
return head;
}
ListNode dummy = new ListNode(0); //new starter of the sorted list
ListNode cur = head; //the node will be inserted
ListNode pre = dummy; //insert node between pre and pre.next
ListNode next = null; //the next node will be inserted
//not the end of input list
while( cur != null ){
next = cur.next;
//find the right place to insert
while( pre.next != null && pre.next.val < cur.val ){
pre = pre.next;
}
//insert between pre and pre.next
cur.next = pre.next;
pre.next = cur;
pre = dummy;
cur = next;
}
return dummy.next;
}
public static void print(ListNode head){
while(head != null){
System.out.println(head.val);
head = head.next;
}
}
public static void main(String[] args) {
ListNode l1 = new ListNode(3);
ListNode l2 = new ListNode(4);
ListNode l3 = new ListNode(2);
ListNode l4 = new ListNode(1);
ListNode l5 = new ListNode(5);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
print(insertionSortList(l1));
}
}