【LeetCode】Insertion Sort List

來源:互聯網
上載者:User

標籤:leetcode   algorithm   java   插入排序   鏈表   

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; *     } * } */

【思路】

基礎題。痛點在於理解鏈表結,因為 next 既是當前 node 的屬性,又表示下一個 node。

在 head 之前添加一個新的頭 newhead,因為插入排序時可能有 node 要插在 head 之前,這時就需要這個 newhead 的協助。

【Java代碼】

public class Solution {    public ListNode insertionSortList(ListNode head) {        if (head == null || head.next == null) return head;//新手很容易忽略這一行                ListNode newhead = new ListNode(0);        newhead.next = head;//在head前添加一個新頭newhead        ListNode p = head.next;//遍曆從第二個node開始        head.next = null;//目前已排序的鏈表只有newhead和head兩個結點,這樣做的好處是如果後面插入的結點都在head之前,那麼可以保證排完序的鏈表結尾指向null                while (p != null) {//用p遍曆還未排序的鏈表                        ListNode cur = p;            p = p.next;            cur.next = null;//如果這個結點需要查到鏈表的最後,這樣做可以保證鏈表結尾指向null                        ListNode node = newhead.next;            ListNode pre = newhead;                        while (node != null) {//用node遍曆已排好序的鏈表,pre表示遍曆時當前項的前一項                if (cur.val < node.val) {//在該插入的位置插入cur                    pre.next = cur;                    cur.next = node;                    break;                } else {//還未到插入的位置,繼續向後,同時更新pre                    pre = node;                    node = node.next;                }                                if (node == null) {//如果插入的位置在鏈表末尾                    pre.next = cur;                }            }        }                return newhead.next;    }}

不多說了,捋清思路,分清楚哪個是變數,哪個是鏈表中的項。混亂時不妨從頭再來。


【LeetCode】Insertion Sort List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.