method 1 dummy node
/**
* 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) {
ListNode* dummyNode = new ListNode(0);
dummyNode->next = l1;
l1 = dummyNode;
while((l2 != NULL)&&(l1->next != NULL))
{
if (l1->next->val > l2->val)
{
ListNode* tempNode = l2->next;
l2->next = l1->next;
l1->next = l2;
l2 = tempNode;
}
else
{
l1 = l1->next;
}
}
if ((l1->next == NULL) /*&& (l2!= NULL)*/)
{
l1->next = l2;
}
return dummyNode->next;
}
};