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

 

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12         ListNode *p,*res;
13         int val1,val2;
14          if(l1==NULL&&l2==NULL)
15          {p=NULL;return p;}
16          if(l1==NULL&&l2!=NULL)
17          {p=l2;return p;}
18          if(l1!=NULL&&l2==NULL) 
19          {p=l1;return p;}
20          
21          if(l1->val<l2->val)
22             {
23                 p=l1;
24                 l1=l1->next;
25             }
26             else
27             {
28                 p=l2;
29                 l2=l2->next;
30             }
31         res=p;
32         while(l1!=NULL||l2!=NULL)
33         {
34             if(l1==NULL)
35             val1=INT_MAX;
36             else
37             val1=l1->val;
38             if(l2==NULL)
39             val2=INT_MAX;
40             else
41             val2=l2->val;
42             if(val1<val2)
43             {
44                 p->next=l1;
45                 l1=l1->next;
46                 p=p->next;
47             }
48             else
49             {
50                 p->next=l2;
51                 l2=l2->next;
52                 p=p->next;
53             }
54             
55         }
56         
57         return res;
58         
59     }
60 };