Skip to content

Instantly share code, notes, and snippets.

@honux77
Created June 14, 2014 18:55
Show Gist options
  • Select an option

  • Save honux77/bf7ee8f67c65132a91a1 to your computer and use it in GitHub Desktop.

Select an option

Save honux77/bf7ee8f67c65132a91a1 to your computer and use it in GitHub Desktop.
Linked List Insertion Sort
/**
* https://oj.leetcode.com/problems/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) {
ListNode n = head;
while (n != null && n.next != null) {
ListNode target = n.next;
if (n.val > target.val) {
n.next = target.next;
head = findAndReplace(head, target);
} else
n = n.next;
}
return head;
}
public ListNode findAndReplace(ListNode head, ListNode target) {
ListNode n = head;
ListNode prev = null;
while(n != null) {
if(n.val > target.val ) {
target.next = n;
if(prev == null)
head = target;
else
prev.next = target;
break;
}
prev = n;
n = n.next;
}
return head;
}
}
@honux77
Copy link
Copy Markdown
Author

honux77 commented Jun 14, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment