题目链接:https://leetcode.com/problems/merge-two-sorted-lists/
题目描述:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Subscribe to see which companies asked this question
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL || l2 == NULL) return l1 == NULL ? l2 : l1;
ListNode *p = l1->next, *q = l2->next;
ListNode *head=new ListNode(0);//合并后的表头前一个附加节点,返回的时候去掉即可
ListNode *tmp=head;//移动的指针
while(1)
{
if(l2->val<=l1->val)
{
tmp->next=l2;
tmp=l2;
l2=q;
if(l2==NULL)
{
tmp->next=l1;
return head->next;
}
q=q->next;
}
else
{
tmp->next=l1;
tmp=l1;
l1=p;
if(l1==NULL)
{
tmp->next=l2;
return head->next;
}
p=p->next;
}
}
}
};