欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Merge Two Sorted Lists(C++)

程序员文章站 2022-03-26 19:48:11
merge two sorted linked lists and return it as a new list. the new list should be made by splicing...

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.

/**
* 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)
{
if(l1==null)
return l2;
if(l2==null)
return l1;
listnode* result=new listnode(0);
listnode* cur=result;
while(l1!=null&&l2!=null)
{
if(l1->valval)
{
cur->next=l1;
l1=l1->next;
}
else
{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
while(l1==null&&l2!=null)
{
cur->next=l2;
l2=l2->next;
cur=cur->next;
}
while(l2==null&&l1!=null)
{
cur->next=l1;
l1=l1->next;
cur=cur->next;
}
return result->next;
}
};