Insertion Sort List

来源:互联网 发布:云计算超强计算能力 编辑:程序博客网 时间:2024/05/08 05:52

Sort a linked list using insertion sort.

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == null || head.next == null) {            return head;        }                ListNode dummyHead = new ListNode(Integer.MIN_VALUE);        ListNode h1 = dummyHead;        ListNode h2 = head;        while(h2 != null) {            ListNode insertionNode = findInsertionNode(h1, h2);            ListNode originalPostNode = h2.next;            h2.next = insertionNode.next;            insertionNode.next = h2;            h2 = originalPostNode;        }        return dummyHead.next;    }    private ListNode findInsertionNode(ListNode h1, ListNode h2) {        ListNode pre = null;        while(h1 != null && h1.val <= h2.val) {            pre = h1;            h1 = h1.next;        }        return pre;    }}


0 0