1. 程式人生 > >LeetCode-147. 對連結串列進行插入排序

LeetCode-147. 對連結串列進行插入排序

題目

對連結串列進行插入排序。

在這裡插入圖片描述
插入排序的動畫演示如上。從第一個元素開始,該連結串列可以被認為已經部分排序(用黑色表示)。
每次迭代時,從輸入資料中移除一個元素(用紅色表示),並原地將其插入到已排好序的連結串列中。

插入排序演算法:

插入排序是迭代的,每次只移動一個元素,直到所有元素可以形成一個有序的輸出列表。
每次迭代中,插入排序只從輸入資料中移除一個待排序的元素,找到它在序列中適當的位置,並將其插入。
重複直到所有輸入資料插入完為止。

示例 1:

輸入: 4->2->1->3
輸出: 1->2->3->4

示例 2:

輸入: -1->5->3->4->0
輸出: -1->0->3->4->5

解題

  • 插入排序寫法如下
  • 這題使用歸併排序寫也能過, 而且效能更高, 不過題目要求使用插入排序, 這裡就使用插入排序來做了
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummyHead =
new ListNode(0); dummyHead.next = head; // head~pre是排好序的部分 ListNode pre = head; // 第一個元素預設是有序的 ListNode cur = head.next; while (cur != null) { // 尋找插入位置 ListNode insertPre = findInsertIndexPre(dummyHead, cur); // 這種情況表示當前節點不需要換位置
if (insertPre == pre) { pre = cur; cur = cur.next; } else { // cur的需要插入到insertPre後面的位置 pre.next = cur.next; cur.next = insertPre.next; insertPre.next = cur; // 移動cur cur = pre.next; } } return dummyHead.next; } /** * 查詢cur要插入位置的前一個節點 * @param head * @param cur * @return */ private ListNode findInsertIndexPre(ListNode head, ListNode cur ){ while (head.next != cur) { if (head.next.val >= cur.val) { return head; } head = head.next; } return head; } }