/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head,*curr,*p,*q;
p=l1;
q=l2;
head=curr=NULL;
while(p&&q)
{
if(!head)
{
int temp=l1->val>l2->val?l2->val:l1->val;
head=new ListNode(temp);
curr=head;
}
else
{
int temp=p->val>q->val?q->val:p->val;
curr->next=new ListNode(temp);
curr=curr->next;
}
if(p->val>q->val)
q=q->next;
else
p=p->next;
}
if(p)
{
if(head)
curr->next=p;
else
head=p;
}
else if(q)
{
if(head)
curr->next=q;
else
head=q;
}
return head;
}
};
leetcode 21: Merge Two Sorted Lists
最新推荐文章于 2022-05-22 13:07:29 发布