您的位置:首页 > 其它

合并两个排序的链表

2016-05-09 00:00 190 查看

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

递归

[code=plain]class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* node=NULL;
if(pHead1==NULL)
{
return node=pHead2;
}
if(pHead2==NULL)
{
return node=pHead1;
}
if(pHead1->val>pHead2->val){
node=pHead2;
node->next=Merge(pHead1,pHead2->next);
}else{
node=pHead1;
node->next=Merge(pHead1->next,pHead2);
}
return node;
}
};

非递归

[code=plain]public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//新建一个头节点,用来存合并的链表。
ListNode head=new ListNode(-1);
head.next=null;
ListNode root=head;
while(list1!=null&&list2!=null){
if(list1.val<list2.val){
head.next=list1;
head=list1;
list1=list1.next;
}else{
head.next=list2;
head=list2;
list2=list2.next;
}
}
//把未结束的链表连接到合并后的链表尾部
if(list1!=null){
head.next=list1;
}
if(list2!=null){
head.next=list2;
}
return root.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: