Q:输入两个单调递增的链表,输出两个链表合成后的链表,使合成后的链表也满足单调递增
输入:
A:2->4->6->7->10
B:1->2->3->8->9
输出:
1->2->2->3->4->6->7->8->9->10
代码:
定义链表节点:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
合成链表:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* head=new ListNode(0);
head->next=NULL;
ListNode* cur=head;
while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val>=pHead2->val)
{
cur->next=pHead2;
cur=cur->next;
pHead2=pHead2->next;
}
else
{
cur->next=pHead1;
cur=cur->next;
pHead1=pHead1->next;
}
}
if(pHead1)
cur->next=pHead1;
if(pHead2)
cur->next=pHead2;
return head->next;
}
};