【题目描述】
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
【思路】
定义一个新的头节点,然后利用迭代,对比两个链表的头部,将较小的插入到新的头节点的后面,知道两个链表中有一个或者两个被遍历完毕。再将未被遍历完毕的链表剩余部分,接在新的头节点的链表尾部即可。时间复杂度O(min(m,n)),m,n为两个链表的长度。
【代码】
C++:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* newhead=new ListNode(-1);
ListNode* cur=newhead;
while(pHead1!=NULL and pHead2!=NULL){
if(pHead1->val<pHead2->val){
cur->next=pHead1;
pHead1=pHead1->next;
}else{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;
}
if(pHead1!=NULL){
cur->next=pHead1;
}else if(pHead2!=NULL){
cur->next=pHead2;
}
return newhead->next;
}
};
Python:
class Solution:
def Merge(self, pHead1, pHead2):
pHead=ListNode(-1)
Head=pHead
while(pHead1 and pHead2):
if pHead1.val>pHead2.val:
pHead.next=pHead2
pHead2=pHead2.next
else:
pHead.next=pHead1
pHead1=pHead1.next
pHead=pHead.next
pHead.next=pHead1 or pHead2
return Head.next