首页 > 试题广场 >

已知两个链表list1 和list2 内的数据都是有序...

[问答题]

已知两个链表list1 list2 内的数据都是有序的,请把它们合并成一个链表,保持里面的数据依然有序,要求用递归的方法实现()。下面是定义的链表的节点:

struct Node {
int data;
Node *next;
};
typedef struct Node Node;

请写出函数Node * MergeRecursive(Node *head1, Node *head2)的实现。
Node *MergeRecursive(Node *head1,Node *head2)
{
 if(head1==nullptr&&head2==nullptr)
    return nullptr;
 else if(head1==nullptr)
   return head2;
 else if(head2==nullptr)
  return head1;
 else if(head1->val<=head2->val)
    head1->next =MergeRecursive(head1->next,head2);
 else 
   head2->next =MergeRecursive(head1,head2->next);
}
发表于 2019-02-21 15:39:34 回复(0)
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 递归的结束条件(递归出口),也就是某一个链表被遍历到最后一个节点
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        // 值小的连接到大的值大的那一个链表后面
        if(l1.val < l2.val){
            // 就是如果l1的值小于l2的节点值,就找l1的下一个节点进行递归比较插入到l2,因为是都是有序链表
            l1.next = mergeTwoLists(l1.next, l2);
            // 将l1返回为了判断l1是否遍历完
            return l1;
        }else{
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

发表于 2020-10-28 23:14:49 回复(0)

Node *MergeRecursive(Node *head1,Node *head2)
{
 if(head1==nullptr&&head2==nullptr)
    return nullptr;
 else if(head1==nullptr)
   return head2;
 else if(head2==nullptr)
  return head1;
 else if(head1->val<=head2->val)
    head1->next =MergeRecursive(head1->next,head2);
 else 
   head2->next =MergeRecursive(head1,head2->next);
}
发表于 2019-06-03 22:15:11 回复(0)
def Merge(self, pHead1, pHead2):
    if pHead1 == None:
         return pHead2
    if pHead2 == None:
         return pHead1
    pMergeHead = None
    if pHead1.val < pHead2.val:
        pMergeHead = pHead1
        pMergeHead = self.Merge(pHead1.next, pHead2)
    else:
        pMergeHead = pHead2
        pMergeHead = self.Merge(pHead1, pHead2.next)
    return pMergeHead

发表于 2019-02-28 22:29:06 回复(0)