Merge Two Sorted Lists

題目:
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;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章