代码nullMerge two sorted linked lists
在写这篇文章之前,xxx已经写过了几篇关于改代码null主题的文章,想要了解的朋友可以去翻一下之前的文章
标题:
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.
代码如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL)return l2;
if(l2==NULL)return l1;
ListNode *head1=NULL,*head2=NULL;
if(l1->val<=l2->val)
{
head1=l1;
head2=l2;
}
else
{
head1=l2;
head2=l1;
}
ListNode *head=head1;
while(head2!=NULL)
{
while(head1->next!=NULL&&head1->next->val<=head2->val)
{
head1=head1->next;
}
if(head1->next==NULL)
{
head1->next=head2;
break;
}
else
{
ListNode *tmp=head2;
head2=head2->next;
tmp->next=head1->next;
head1->next=tmp;
head1=tmp;
}
}
return head;
}
文章结束给大家分享下程序员的一些笑话语录:
人在天涯钻,哪儿能不挨砖?日啖板砖三百颗,不辞长做天涯人~