Created
September 24, 2014 03:15
-
-
Save sreeprasad/fb7315b77eaf509b3125 to your computer and use it in GitHub Desktop.
Insertion Sort Linked 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 newHead = null; | |
while(head!=null){ | |
ListNode curr = head; | |
head = head.next; | |
if( newHead ==null || curr.val<newHead.val ){ | |
curr.next = newHead; | |
newHead = curr; | |
}else{ | |
ListNode p = newHead; | |
while(p!=null){ | |
if( p.next==null || curr.val<p.next.val ){ | |
curr.next = p.next; | |
p.next = curr; | |
break; | |
} | |
p=p.next; | |
} | |
} | |
} | |
return newHead; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment