标签:
/* * 147. Insertion Sort List * 2016-6-1 by Mingyang * insertion sort的基本思路要有,比较巧的一点是,每处理一个点的时候,把下面一个点用next存起来 * 这样的话,下次就可以直接对next进行处理,然后里面第二个while循环只用包含一种情况,另一种情况break * 实际上就不用写下来了 */ public ListNode insertionSortList(ListNode head) { if (head == null) { return head; } ListNode helper = new ListNode(0); // new starter of the sorted list ListNode cur = head; // the node will be inserted ListNode pre = helper; // insert node between pre and pre.next ListNode next = null; // the next node will be inserted // not the end of input list while (cur != null) { next = cur.next; // find the right place to insert while (pre.next != null && pre.next.val < cur.val) { pre = pre.next; } // insert between pre and pre.next cur.next = pre.next; pre.next = cur; // 让pre与cur回归原来的位置 pre = helper; cur = next; } return helper.next; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5551807.html