【题目】
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
来源:leetcode
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
【示例】
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
【代码】
【常规法】
/**
* 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&&!l2)||(!l1&&!l2))
return l1;
if(!l1&&l2)
return l2;
ListNode*node=NULL,*nownode=NULL;
while(l1&&l2){
if(l1->val<=l2->val){
if(node==NULL){
node=nownode=l1;
}else{
nownode->next=l1;
nownode=l1;
}
l1=l1->next;
}else{
if(node==NULL)
node=nownode=l2;
else{
nownode->next=l2;
nownode=l2;
}
l2=l2->next;
}
}
if(l1)
nownode->next=l1;
else
nownode->next=l2;
return node;
}
};
【代码略简】
/**
* 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 {
private:
vector<int> v;
public:
void deal(ListNode*l1,ListNode*l2,int flag){
ListNode* pre;
while(l1){
v.push_back(l1->val);
pre=l1;
l1=l1->next;
}
if(flag)
pre->next=l2;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1&&!l2)
return l1;
if(!l1&&l2)
return l2;
if(!l1&&!l2)
return l1;
int cnt;
ListNode *node=l1;
deal(l1,l2,1);
deal(l2,NULL,0);
sort(v.begin(),v.end());
while(node){
node->val=v[cnt++];
node=node->next;
}
return l1;
}
};