1. Title description
The two merged into a new list in ascending order of ascending list and returns. The new linked list is composed by splicing all the nodes of the given two linked lists.
Example:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
Two, problem-solving ideas
-
First determine whether there is an empty list
if(l1==nullptr) return l2; if(l2==nullptr) return l1;
-
Determine the head node of the merged linked list (the node with a small integer value)
ListNode* head; l1->val>l2->val ? (head=l2,l2=l2->next):(head=l1,l1=l1->next);
-
Connect subsequent nodes
while(l1!=nullptr&&l2!=nullptr){ l1->val>l2->val ? (p->next=l2,l2=l2->next):(p->next=l1,l1=l1->next); p=p->next; }
Three, my code
/**
* 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) {
if(l1==nullptr)
return l2;
if(l2==nullptr)
return l1;
ListNode* head;
l1->val>l2->val ? (head=l2,l2=l2->next):(head=l1,l1=l1->next);
ListNode* p=head;
while(l1!=nullptr&&l2!=nullptr){
l1->val>l2->val ? (p->next=l2,l2=l2->next):(p->next=l1,l1=l1->next);
p=p->next;
}
p->next=(l1==nullptr)? l2:l1;
return head;
}
};