当前位置:网站首页>21. Merge two ordered linked lists
21. Merge two ordered linked lists
2022-07-28 10:52:00 【vv1025】
The difficulty is simple 1983
Merge two ascending linked lists into a new Ascending Link list and return . The new linked list is made up of all the nodes of the given two linked lists .
Example 1:

Input :l1 = [1,2,4], l2 = [1,3,4] Output :[1,1,2,3,4,4]
Example 2:
Input :l1 = [], l2 = [] Output :[]
Example 3:
Input :l1 = [], l2 = [0] Output :[0]
Tips :
- The range of the number of nodes in the two linked lists is
[0, 50] -100 <= Node.val <= 100l1andl2All according to Non decreasing order array
/**
* Definition for singly-linked list.
* 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) {
}
};#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Iterative
/// Time Complexity: O(len(l1) + len(l2))
/// Space Complexity: O(1)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummyHead = new ListNode(-1);
ListNode* p = dummyHead;
ListNode* l1p = l1;
ListNode* l2p = l2;
while(l1p != NULL && l2p != NULL){
if(l1p->val < l2p->val){
p->next = l1p;
l1p = l1p->next;
}
else{
p->next = l2p;
l2p = l2p->next;
}
p = p->next;
}
if(l1p != NULL)
p->next = l1p;
else
p->next = l2p;
ListNode* ret = dummyHead->next;
dummyHead->next = NULL;
delete dummyHead;
return ret;
}
};
int main() {
return 0;
}边栏推荐
- 8. Detailed explanation of yarn system architecture and principle
- GKRandom
- Status Notice ¶
- Markdown to word or PDF
- Problems needing attention when VC links static libraries
- GKARC4RandomSource
- Blue Bridge Cup embedded Hal library USART_ RX
- Advanced C language: pointer (1)
- Yan reported an error: could not find any valid local directory for nmprivate/
- GKRandomSource
猜你喜欢
随机推荐
GKNoiseSource
GKVoronoiNoiseSource
3. MapReduce explanation and source code analysis
20200217 training match L1 - 7 2019 is coming (20 points)
Redis-day01-常识补充及redis介绍
AP AUTOSAR platform design 1-2 introduction, technical scope and method
GKPolygonObstacle
GKCylindersNoiseSource
GKConstantNoiseSource
爱可可AI前沿推介(7.28)
剑指 Offer 35. 复杂链表的复制
Blue Bridge Cup embedded Hal library USART_ RX
Start from scratch blazor server (2) -- consolidate databases
GKNoiseMap
GKSphereObstacle
Particle swarm optimization to solve the technical problems of TSP
Yarn报错:Could not find any valid local directory for nmPrivate/
Blue Bridge Cup embedded Hal library USART_ TX
Arduino Basics
float浮动初步理解









