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->4Output: 1->1->2->3->4->4
class Solution { public: ListNode * mergeTwoLists(ListNode* l1, ListNode * l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode * p1 = l1, *p2 = l2, *p, *head = NULL, *q = NULL; while (p1 != NULL && p2 != NULL) { if (p1->val <= p2->val) { p = new ListNode(p1->val); p1 = p1->next; } else { p = new ListNode(p2->val); p2 = p2->next; } if (head == NULL) { head = p; } else { q->next = p; } q = p; } if (p1 != NULL) q->next = p1; else q->next = p2; return head; } };