1. 程式人生 > >LeetCode---Merge Two Sorted Lists

LeetCode---Merge Two Sorted Lists

Question: Merge Two Sorted Lists

Description: 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.


Example:

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

Solution

 

 採用兩個指標指向兩個連結串列,比較指標對應節點的大小,較小的節點即為下一個節點,同時指標指向下一個節點;

Solution Code

/**
 * 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 == nullptr) return l2; else if(l2 == nullptr) return l1; // 兩個連結串列都不為空 ListNode *pMerge = nullptr; if(l1->val < l2->val){ pMerge = l1; pMerge->next = mergeTwoLists(l1->next, l2); }
else{ pMerge = l2; pMerge->next = mergeTwoLists(l1, l2->next); } return pMerge; } };

Reports: Runtime: 8 ms, faster than 89.04% of C++ online submissions for Merge Two Sorted Lists.