题目
Sort a linked list using insertion sort.
思路
典型的插入排序,方法直接看代码
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public static boolean less(ListNode w,ListNode v)
{
return w.val<v.val;
}
public ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode helper = new ListNode(Integer.MIN_VALUE);
ListNode cur = head;
ListNode pre = helper;
ListNode next = null;
while(cur!=null)
{
next = cur.next;//store cur.next
while(pre.next!=null&&less(pre.next,cur))
{
pre = pre.next;
}
//insert cur between pre and pre.next
cur.next = pre.next;
pre.next = cur;
pre = helper;
cur = next;
}
return helper.next;
}
}