- Total Accepted: 219857
- Total Submissions: 567355
- Difficulty: Easy
- Contributor: LeetCode
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.
Subscribe to see which companies asked this question.
/**
* 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) {
ListNode* MNode=new ListNode(NULL);
ListNode* p=MNode;
while(1)
{
if(l1==NULL){p->next=l2;break;}//为什么不能去掉这条在前面加判断?--因为在循环,不能为空结束
if(l2==NULL){p->next=l1;break;}
if(l1->val<l2->val){
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
p=p->next;
}
ListNode* temp=MNode->next;
delete(MNode);
return temp;
}
};
//原链表已改变,保持不变需要进行复制链表