Insertion Sort List
Source
- leetcode: Insertion Sort List
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.
Java
/**
* 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) {
ListNode helper=new ListNode(0);
ListNode pre=helper;
ListNode current=head;
while(current!=null) {
pre=helper;
while(pre.next!=null&&pre.next.val<current.val) {
pre=pre.next;
}
ListNode next=current.next;
current.next=pre.next;
pre.next=current;
current=next;
}
return helper.next;
}
}