博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
21. Merge Two Sorted Lists
阅读量:7031 次
发布时间:2019-06-28

本文共 1167 字,大约阅读时间需要 3 分钟。

 

 

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4Output: 1->1->2->3->4->4

不带头结点

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1 == NULL)            return l2;        if(l2 == NULL)            return l1;        ListNode *first = NULL;        if(l1->val < l2->val) {            first = l1;            l1 = l1->next;        } else {            first = l2;            l2 = l2->next;        }        ListNode *last = first;        while(l1 && l2) {            if(l1->val < l2->val) {                last->next = l1;                l1 = l1->next;            } else {                last->next = l2;                l2 = l2->next;            }            last = last->next;        }        if(l1)            last->next = l1;        if(l2)            last->next = l2;        return first;            }};

 

转载于:https://www.cnblogs.com/huwtylv/p/9338831.html

你可能感兴趣的文章
leapMotion简介
查看>>
增量更新项目时的备份MyBak
查看>>
图灵成立七周年——经典回顾
查看>>
iOS常用的设计模式
查看>>
[十二省联考2019]春节十二响
查看>>
HL AsySocket 服务开发框架 - 总体思路与架构
查看>>
安全原理
查看>>
web前端中的一些注释表达法
查看>>
Kotlin学习与实践 (八)集合的函数式 lambda API
查看>>
Kotlin学习与实践 (三)fun 函数
查看>>
[原]Unity3D深入浅出 - 脚本开发基础(Scripts)
查看>>
HTTP Error 503. The service is unavailable
查看>>
常用的排序、查找算法的时间复杂度和空间复杂度
查看>>
Android 检测SD卡状态
查看>>
SQL Server 查询所有包含某文本的存储过程、视图、函数
查看>>
Error response from daemon: conflict: unable to remove repository reference 解决方案
查看>>
【Dijkstra】CCF201609-4 交通规划
查看>>
loadRunner11的安装过程
查看>>
什么是shell
查看>>
boost-同步-锁选项
查看>>