这道题主要考察的是对指针的熟悉程度。
具体解题思想参考剑指offer 25.
时间和内存消耗以及源代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (l1 == NULL)
{
return l2;
}
if (l2 == NULL)
{
return l1;
}
struct ListNode* pNode;
if (l1->val > l2->val)
{
pNode = l2;
l2 = l2->next;
}
else
{
pNode = l1;
l1 = l1->next;
}
struct ListNode* pReverse = pNode;
while (l1 != NULL && l2 != NULL)
{
if (l1->val > l2->val)
{
pNode->next = l2;
l2 = l2->next;
}
else
{
pNode->next = l1;
l1 = l1->next;
}
pNode = pNode->next;
}
if (l1 == NULL)
{
pNode->next = l2;
}
else
{
pNode->next = l1;
}
return pReverse;
}