题目: 给出两个排序的单链表,合并两个单链表,返回合并后的结果;
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;
}
}
};