题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
提交代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead2==NULL)
{
return pHead1;
}
if (pHead1==NULL)
{
return pHead2;
}
//不大的为怕p1_fast;
if (pHead1->val>pHead2->val)
{
ListNode* p1_fast = pHead2;
ListNode* p2_fast = pHead1;
}
ListNode* p1_fast = pHead1;
ListNode* p2_fast = pHead2;
ListNode* p = p1_fast;
ListNode* p_out = p1_fast;
p1_fast = p1_fast->next;
while (p1_fast!=NULL)
{
if (p2_fast == NULL)
{
p->next = p1_fast;
return p_out;
}
if (p1_fast->val>p2_fast->val)
{
p->next = p2_fast;
p = p2_fast;
p2_fast = p2_fast->next;
}
else
{
p->next = p1_fast;
p = p1_fast;
p1_fast = p1_fast->next;
}
}
p->next = p2_fast;
return p_out;
}
};
测试代码:
int main()
{
Solution *s = new Solution();
//vector<int> v = { 2,4,6,1,3,5,7 };
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(6);
ListNode *l3 = new ListNode(8);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
ListNode *l6 = new ListNode(6);
ListNode *l7 = new ListNode(7);
l1->next = l2;
l2->next = l3;
//l3->next = l4;
l4->next = l5;
l5->next = l6;
l6->next = l7;
ListNode* out_list =s->Merge(l1,l4);
system("pause");
return 0;
}
结果: