以下是一个示例代码:

#include <iostream>

using namespace std;

// 定义单链表的结构体
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        // 如果其中一个链表为空,则直接返回另一个链表
        if (!l1) {
            return l2;
        }
        if (!l2) {
            return l1;
        }

        // 定义一个哨兵节点,方便操作
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;

        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            } else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }

        // 将剩余的节点接到新链表的末尾
        if (l1) {
            cur->next = l1;
        }
        if (l2) {
            cur->next = l2;
        }

        return dummy->next;
    }
};

int main() {
    // 创建两个链表
    ListNode* l1 = new ListNode(1);
    l1->next = new ListNode(3);
    l1->next->next = new ListNode(5);

    ListNode* l2 = new ListNode(2);
    l2->next = new ListNode(4);
    l2->next->next = new ListNode(6);

    // 合并两个链表
    Solution solution;
    ListNode* mergedList = solution.mergeTwoLists(l1, l2);

    // 输出合并后的链表
    while (mergedList) {
        cout << mergedList->val << " ";
        mergedList = mergedList->next;
    }
    cout << endl;

    return 0;
}

输出结果为:

1 2 3 4 5 6
``
C++两个单链表合并为一个单链表且无需排序

原文地址: https://www.cveoy.top/t/topic/fiWG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录