leetcode Merge Two Sorted Lists
/**
* 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;
ListNode *p=l1,*q=l2;
if(p==NULL)return q;
if(q==NULL)return p;
if(p->val<q->val)
{
head=p;
p=p->next;
}
else
{
head=q;
q=q->next;
}
ListNode *r=head;
while(p&&q)
{
if(p->val<q->val)
{
r->next=p;
p=p->next;
}
else
{
r->next=q;
q=q->next;
}
r=r->next;
}
if(p==NULL)
{
r->next=q;
}
if(q==NULL)
{
r->next=p;
}
return head;
}
};
题目很容易,但是要写出没有bug的代码却不容易。
浙公网安备 33010602011771号