題目:
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.
思路:
1、首先判斷邊界條件,看是否兩個都爲NULL,或者是否有其中一個爲NULL;
2、新建一個新的結點,結點指向下一個元素(val較小的那個),進行迭代;
代碼:
/**
* 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 && l2!=NULL)
{
return l2;
}
if(l1!=NULL && l2==NULL)
{
return l1;
}
ListNode *tmp=NULL;
if(l1->val<l2->val)
{
tmp=l1;
tmp->next=mergeTwoLists(l1->next,l2);
}
else if(l1->val>=l2->val)
{
tmp=l2;
tmp->next=mergeTwoLists(l1,l2->next);
}
return tmp;
}
};