Created
June 14, 2014 18:55
-
-
Save honux77/bf7ee8f67c65132a91a1 to your computer and use it in GitHub Desktop.
Linked List Insertion Sort
This file contains hidden or 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
| /** | |
| * 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; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://oj.leetcode.com/problems/insertion-sort-list/