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;
}
相关推荐
2301_82237765几秒前
模板元编程调试方法
开发语言·c++·算法
啟明起鸣14 分钟前
【C++ 性能提升技巧】C++ 的引用、值类型、构造函数、移动语义与 noexcept 特性,可扩容的容器
开发语言·c++
故以往之不谏16 分钟前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°24 分钟前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困25 分钟前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van38 分钟前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_8112329843 分钟前
低延迟系统C++优化
开发语言·c++·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
txinyu的博客1 小时前
解析muduo源码之 ThreadLocal.h
c++
橘子师兄1 小时前
C++AI大模型接入SDK—ChatSDK封装
开发语言·c++·人工智能·后端