Created
February 21, 2014 02:56
-
-
Save b27lu/9127973 to your computer and use it in GitHub Desktop.
Insertion Sort List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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