Skip to content

Instantly share code, notes, and snippets.

@SleimanJneidi
Created June 17, 2014 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SleimanJneidi/dd32fce1f9385b51a21f to your computer and use it in GitHub Desktop.
Save SleimanJneidi/dd32fce1f9385b51a21f to your computer and use it in GitHub Desktop.
/**
* 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