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;
}
相关推荐
老四啊laosi8 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
妙为9 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
小白菜又菜11 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
史迪仔011212 小时前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
会编程的土豆13 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
低频电磁之道13 小时前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
songyuc14 小时前
BM2『链表内指定区间反转』学习笔记
学习·链表
君义_noip15 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus15 小时前
静态链接与动态链接
c++
摸个小yu15 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表