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.
#include<iostream>
#include<vector>
using namespace std;
//Definition for singly - linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode*ResultList = new ListNode(0);
ListNode*ResultHead = ResultList;
ListNode*Tmpl1 = l1;
ListNode*Tmpl2 = l2;
while (Tmpl1!=NULL&&Tmpl2!=NULL){
if (Tmpl1->val<=Tmpl2->val){
ResultHead->next = Tmpl1;
Tmpl1 = Tmpl1->next;
}
else{
ResultHead->next = Tmpl2;
Tmpl2 = Tmpl2->next;
}
ResultHead = ResultHead->next;
}
if (Tmpl1 == NULL&&Tmpl2 != NULL)
ResultHead->next = Tmpl2;
else if (Tmpl1 != NULL&&Tmpl2 == NULL)
ResultHead->next = Tmpl1;
return ResultList->next;
}