LeetCode HOT100 - 合并两个有序链表

前面一道链表的弱化版

看作各有一个指针指向链表

当前哪个元素小就接上哪个

肯定有一个先使用完

这时候剩下的那个就全部接到末尾

/**
 * 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* x, ListNode* y) {
        ListNode* res = new ListNode(), *cur;
        cur = res;
        while (x && y) {
            if (x->val < y->val) {
                cur->next = x;
                x = x->next;
            } else {
                cur->next = y;
                y = y->next;
            }
            cur = cur->next;
        }
        cur->next = x ? x : y;
        return res->next;
    }
};
posted @ 2026-04-16 23:12  rdcamelot  阅读(11)  评论(0)    收藏  举报