当前位置: 移动技术网 > IT编程>开发语言>C/C++ > Merge Two Sorted Lists(C++)

Merge Two Sorted Lists(C++)

2018年10月05日  | 移动技术网IT编程  | 我要评论

思春期狂想曲,b型h系全集,t-ara 小苹果

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;
}
};

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网