【Leetcode刷题】--链表--leetcode21.融合两个有序链表

题目: 给出两个排序的单链表,合并两个单链表,返回合并后的结果;

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解法:

解法还是很简单的,但是需要注意以下几点:

1.  如果两个链表都空,则返回null;

2.  如果链表1空,则返回链表2的头节点;反之,如果链表2为空,则返回链表1的头节点;

3.  两个链表都不空的情况下:

   比较两个链表的头节点的值,哪个小,则新链表的头节点为哪个;

  举例:l1: 1->3->5; l2:2->4->6->7;则:head = l1的头节点,此时head.next = l1.next 或者 l2

 

/**
 * 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&&l2==NULL)
        return NULL;
    if(l1==NULL)
        return l2;
    if(l2==NULL)
        return l1;
    ListNode *head=NULL;
    if(l1->val<l2->val){
        head=l1;
        head->next=mergeTwoLists(l1->next,l2);     
    }
    else{
        head=l2;
        head->next=mergeTwoLists(l1,l2->next);
    }
    return head;
}
};
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==NULL && pHead2==NULL)
            return NULL;
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        if(pHead1->val<pHead2->val){
            pHead1->next=Merge(pHead1->next,pHead2);
            return pHead1;
        }else{
            pHead2->next=Merge(pHead1,pHead2->next);
            return pHead2;
        }
            
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值