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;
}
相关推荐
新手小新14 分钟前
C++游戏开发(2)
开发语言·前端·c++
杰克尼42 分钟前
11. 盛最多水的容器
算法·leetcode·职场和发展
程序员编程指南2 小时前
Qt 嵌入式界面优化技术
c语言·开发语言·c++·qt
逝雪Yuki3 小时前
数据结构与算法——字典(前缀)树的实现
数据结构·c++·字典树·前缀树·左程云
技术思考者3 小时前
Leetcode - 反转字符串
数据结构·算法·leetcode
卷卷的小趴菜学编程3 小时前
Qt-----初识
开发语言·c++·qt·sdk·qt介绍
程序员编程指南4 小时前
Qt 开发 IDE 插件开发指南
c语言·c++·ide·qt·elasticsearch
利刃大大5 小时前
【在线五子棋对战】十一、整合封装服务器模块实现
运维·服务器·c++·项目·五子棋
ok0605 小时前
C++对象访问有访问权限是不是在ide里有效
开发语言·c++·ide
程序员编程指南6 小时前
Qt 开发自动化测试框架搭建
c语言·开发语言·c++·qt