一、問題描述
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
二、解題思路
遍歷兩個鏈表,然後比較大小。小的加上,然後繼續比較。直到其中一個到達尾部,那麼就把剩下的鏈表直接加上。
三、代碼實現
/**
* 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;
else if(l1 != NULL && l2 == NULL) return l1;
else if(l1 == NULL && l2 != NULL) return l2;
else {
ListNode* preHead = new ListNode(0);
//preHead 需要移動,因此使用resultHead來先保存下
ListNode* resultHead = preHead;
while( l1!=NULL && l2!=NULL){
//同時不爲空,那就比較。然後將小的添加到preHead的尾部
if(l1->val < l2->val){
preHead->next = l1;
preHead = preHead->next;
l1 = l1->next;
}else{
preHead->next = l2;
preHead = preHead->next;
l2 = l2->next;
}
//while結束,說明有一個爲空了,那就把不爲空的直接加上
if(l1!=NULL) preHead->next = l1;
if(l2!=NULL) preHead->next = l2;
}
return resultHead->next;
}
}
};