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.
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *vHead = new ListNode(-1);//virtualHead;
ListNode *tmp = vHead;
ListNode *tmp_A = l1;
ListNode *tmp_B = l2;
while(tmp_A && tmp_B)
{
if(tmp_A->val<=tmp_B->val)
{
tmp->next = tmp_A;
tmp_A = tmp_A->next;
}
else
{
tmp->next = tmp_B;
tmp_B = tmp_B->next;
}
tmp = tmp->next;
}
while(tmp_A)
{
tmp->next = tmp_A;
tmp_A = tmp_A->next;
tmp = tmp->next;
}
while(tmp_B)
{
tmp->next = tmp_B;
tmp_B = tmp_B->next;
tmp = tmp->next;
}
if(!vHead->next) return NULL;
else return vHead->next;
}
};