15.力扣c++刷题-->合并两个有序链表

cpp 复制代码
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
using namespace std;


  
  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* l1, ListNode* l2)
    {
        ListNode* pHead = new ListNode(-1);
        ListNode* pre = pHead;
        while ((l1 != nullptr) && (l2 != nullptr))
        {
            if (l1->val <=  l2->val)
            {
                pre->next = l1; 
                l1 = l1->next;
            }
            else
            {
                pre->next = l2;
                l2 = l2->next;
            }
            pre = pre->next;
        }
        pre->next = l1 == nullptr ? l2 : l1;

        return pHead->next;
    }
};

int main()
{
    Solution a;
    ListNode* list1 = new ListNode(1);
    list1->next = new ListNode(2);
    list1->next->next = new ListNode(4);
    //list1->next->next->next = new ListNode(7);

    ListNode* list2 = new ListNode(1);
    list2->next = new ListNode(3);
    list2->next->next = new ListNode(4);
    //list2->next->next->next = new ListNode(6);


    ListNode* pHead = a.mergeTwoLists(list1, list2);
    while (pHead != nullptr)
    {
        cout << pHead->val << endl;
        pHead = pHead->next;
    }
    return 0;
}
相关推荐
sheeta19985 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
是小胡嘛7 小时前
C++之Any类的模拟实现
linux·开发语言·c++
Want59510 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
lingggggaaaa10 小时前
免杀对抗——C2远控篇&C&C++&DLL注入&过内存核晶&镂空新增&白加黑链&签名程序劫持
c语言·c++·学习·安全·网络安全·免杀对抗
phdsky10 小时前
【设计模式】建造者模式
c++·设计模式·建造者模式
H_-H10 小时前
关于const应用与const中的c++陷阱
c++
coderxiaohan10 小时前
【C++】多态
开发语言·c++
gfdhy10 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
ceclar12311 小时前
C++范围操作(2)
开发语言·c++
一个不知名程序员www12 小时前
算法学习入门---vector(C++)
c++·算法