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.