Skip to content

Instantly share code, notes, and snippets.

@b27lu
Created February 21, 2014 02:56
Show Gist options
  • Save b27lu/9127973 to your computer and use it in GitHub Desktop.
Save b27lu/9127973 to your computer and use it in GitHub Desktop.
Insertion Sort List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode fakeHead = new ListNode(Integer.MIN_VALUE);
ListNode current = head;
while(current != null){
ListNode next = current.next;
ListNode prev = fakeHead;
//find out the inserting position
while(prev.next != null && prev.next.val <current.val)
prev = prev.next;
//insert into the sorted part
current.next = prev.next;
prev.next = current;
current = next;
}
return fakeHead.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment