【题目】
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
来源:leetcode
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
【示例1】
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
【限制】
0 <= 链表长度 <= 1000
注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/
【思想】
有点二路归并的赶脚
【代码】
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode*rs=NULL,*cur,*pre=NULL;
while(l1&&l2){
if(l1->val<=l2->val){
cur=l1;
l1=l1->next;
}else{
cur=l2;
l2=l2->next;
}
if(rs==NULL){
rs=cur;
pre=cur;
}else{
pre->next=cur;
pre=cur;
}
}
while(l1){
if(rs==NULL)
rs=l1;
else
pre->next=l1;
pre=l1;
l1=l1->next;
}
while(l2){
if(rs==NULL)
rs=l2;
else
pre->next=l2;
pre=l2;
l2=l2->next;
}
return rs;
}
};

1052

被折叠的 条评论
为什么被折叠?



