/**147. Insertion Sort List * @param head * @return 鏈表,使用插入排序 */ public ListNode insertionSortList(ListNode head) { if (head == null) return head; ListNode ret = new ListNode(Integer.MIN_VALUE); ret.next = head; ListNode pre = head; ListNode cur = head.next; while (cur != null) { if (cur.val < pre.val) { ListNode next = cur.next; for (head = ret; head != cur; head = head.next) { if (cur.val >= head.val && cur.val < head.next.val) { pre.next = cur.next; cur.next = head.next; head.next = cur; } } cur = next; } else { pre = cur; cur = cur.next; } } return ret.next; }
ret指向返回的表頭
cur是現在處理的節點,pre為前一個節點
cur從head的下一個節點開始處理,如果cur>pre,說明需要插入:
儲存下一個將要處理的節點為next
從頭開始找到插入點:if (cur.val >= head.val && cur.val < head.next.val)
public ListNode insertionSortList(ListNode head) { if(head == null||head.next == null) return head; ListNode sortedlisthead = new ListNode(0); ListNode cur = head; while(cur!=null){ ListNode next = cur.next; ListNode pre = sortedlisthead; while(pre.next!=null && pre.next.val<cur.val) pre = pre.next; cur.next = pre.next; pre.next = cur; cur = next; } return sortedlisthead.next; }
sorted list是空,把一個元素插入sorted list中。然後,在每一次插入過程中,都是找到最合適位置進行插入。
pre始終指向sorted list的fakehead,cur指向當前需要被插入的元素,next指向下一個需要被插入的元素。
當sortedlist為空白以及pre.next所指向的元素比cur指向的元素值要大時,需要把cur元素插入到pre.next所指向元素之前。否則,pre指標後移。最後返回fakehead的next即可。