Created
June 17, 2014 13:02
-
-
Save SleimanJneidi/dd32fce1f9385b51a21f to your computer and use it in GitHub Desktop.
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) { | |
return null; | |
} | |
ListNode newHead = new ListNode(head.val); | |
ListNode oldCurrent = head.next; | |
while (oldCurrent != null) { | |
ListNode newNode = new ListNode(oldCurrent.val); | |
if (newNode.val <= newHead.val) { | |
newNode.next = newHead; | |
newHead = newNode; | |
} else { | |
ListNode newCurrent = newHead; | |
while (newCurrent != null) { | |
if (newCurrent.next == null || newNode.val <= newCurrent.next.val) { | |
newNode.next = newCurrent.next; | |
newCurrent.next = newNode; | |
break; | |
} | |
newCurrent = newCurrent.next; | |
} | |
} | |
oldCurrent = oldCurrent.next; | |
} | |
return newHead; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment