Problem
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
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL && l2==NULL)
return NULL;
if(l1!=NULL && l2==NULL)
return l1;
if(l1==NULL && l2!=NULL)
return l2;
ListNode* header = NULL;
if(l1->val < l2->val){
header = l1;
l1 = l1->next;
}else{
header = l2;
l2 = l2->next;
};
ListNode* temp = header;
while(l1 || l2){
if(l1==NULL){
temp->next = l2;
break;
}
if(l2==NULL){
temp->next = l1;
break;
}
if(l1->val < l2->val){
temp->next = l1;
l1 = l1->next;
temp = temp->next;
}
else{
temp->next = l2;
l2 = l2->next;
temp = temp->next;
}
}
return header;
}
};
Result

网友评论