iT邦幫忙

2024 iThome 鐵人賽

DAY 25
0
佛心分享-刷題不只是刷題

刷經典 LeetCode 題目系列 第 25

經典LeetCode 21. Merge Two Sorted Lists

  • 分享至 

  • xImage
  •  

題目 21:「合併兩個有序鏈結串列 (Merge Two Sorted Lists)」 是一道經典的鏈結串列操作問題。目標是將兩個已經排序好的單向鏈結串列合併成一個新的排序鏈結串列。

題目:

給定兩個排序的單向鏈結串列 l1l2,將它們合併成一個新的排序鏈結串列。新鏈結串列是由這兩個鏈結串列的所有節點組成,並且也是有序的。

範例:

  1. 輸入:l1 = [1,2,4]l2 = [1,3,4]

    • 輸出:[1,1,2,3,4,4]
  2. 輸入:l1 = []l2 = []

    • 輸出:[]
  3. 輸入:l1 = []l2 = [0]

    • 輸出:[0]

解題思路

從list1與list2中選擇一個較小的作為root起始,curr作為root list上當前的節點,然後每次都比較當前的list1-val與list2-val誰比較小,較小者就接在curr之後,這樣結果就會是由小到大排列的list,

一開始可以先處理一些邊界情況,

實作:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if (list1 == nullptr && list2 == nullptr) {
            return nullptr;
        }
        if (list1 == nullptr) {
            return list2;
        }
        if (list2 == nullptr) {
            return list1;
        }

        ListNode* curr;

        if (list1->val < list2->val) {
            curr = list1;
            list1 = list1->next;
        } else {
            curr = list2;
            list2 = list2->next;
        }

        ListNode* root = curr;

        while (list2 != nullptr && list1 != nullptr) {
            if (list1->val < list2->val) {
                curr->next = list1;
                list1 = list1->next;
            } else {
                curr->next = list2;
                list2 = list2->next;
            }
            curr = curr->next;
        }

        // list1 is nullptr or list2 is nullptr
        // 當其中一個鏈結串列遍歷完,直接接上剩下的另一個鏈結串列
        if (list1 == nullptr) {
            curr->next = list2;
        } else {
            curr->next = list1;
        }

        return root;
    }
};

參考:
#21. Merge Two Sorted Lists


上一篇
經典LeetCode 141. Linked List Cycle
下一篇
經典LeetCode 19. Remove Nth Node From End of List
系列文
刷經典 LeetCode 題目36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言