insertion sort not quite understand

来源:互联网 发布:手工西装淘宝 编辑:程序博客网 时间:2024/06/02 00:22
/** * 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(-2147483648);        //dummyHead.next = head;        ListNode p1 = dummyHead, p2 = head;                while(p2 != null){            ListNode pre = findInsertPlace(p1, p2);            // insert into list            // save orignal list next node            ListNode originalNext = p2.next;            p2.next = pre.next;            pre.next = p2;                        p2 = originalNext;        }                return dummyHead.next;    }        public ListNode findInsertPlace(ListNode p1, ListNode p2){        ListNode pre = null, cur = p1;        while(cur != null && cur.val <= p2.val){            pre = cur;            cur = cur.next;        }        return pre;    }}

0 0
原创粉丝点击