题目描述如下:
这道题很容易想到通过比较单个链表对应的值,选择小的值填入新的链表中,并往后迭代一次。做题时碰到的问题是创建新的链表时,使用head=head->next导致head链表没有连续起来,已知都是大小为1。所以需要两个链表联合使用。
即:
void add(ListNode*& head, ListNode*& cur, ListNode*& s)
{
if (head == NULL)
{
head = new ListNode(s->val);
cur = head;
s = s->next;
}
else
{
cur->next = new ListNode(s->val);
cur = cur->next;
s = s->next;
}
}
详细代码如下所示:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* p = l1;
ListNode* q = l2;
ListNode* head = NULL;
ListNode* cur = NULL;
while (p != NULL || q != NULL)
{
if (p == NULL)
{
add(head, cur, q);
}
else if (q == NULL)
{
add(head, cur, p);
}
else
{
if (p->val <= q->val)
{
add(head, cur, p);
}
else
{
add(head, cur, q);
}
}
}
return head;
}