一、问题描述
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;
}
}
};