巡覽兩個陣列,依照小到大比對將他們接起來,接到一邊沒有值後就把另外一邊直接整個接上去即可,就不用再巡覽每個剩下的值了。
C++(8ms)
/*******************************************************/
/* LeetCode 21. Merge Two Sorted Lists */
/* Author: Maplewing [at] knightzone.studio */
/* Version: 2018/10/15 */
/*******************************************************/
/**
* 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) {
ListNode headNode(-1);
ListNode* mergeList = &headNode;
ListNode* currentNode = mergeList;
while(l1 != NULL && l2 != NULL){
if(l1->val < l2->val){
currentNode->next = l1;
l1 = l1->next;
}
else{
currentNode->next = l2;
l2 = l2->next;
}
currentNode = currentNode->next;
}
currentNode->next = (l1 != NULL) ? l1 : l2;
return mergeList->next;
}
};
[…] #LeetCode:21. Merge Two Sorted Lists […]