一、比较大小一个一个结点插入
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
ListNode* nHead = new ListNode(0);
ListNode* node = nHead;
while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val<=pHead2->val)
{
node->next = pHead1;
pHead1 = pHead1->next;
}
else
{
node->next = pHead2;
pHead2 = pHead2->next;
}
node = node->next;
}
//这个地方一脑抽写成pHead1了...
if(pHead1==NULL)node->next = pHead2;
else node->next = pHead1;
return nHead->next;
}
};



京公网安备 11010502036488号