[LeetCode] 147. Insertion Sort List java__插入排序

來源:互聯網
上載者:User
    /**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即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.