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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(l1 == NULL && l2 == NULL) return NULL; if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *root, *last, *t_l1 = l1, *t_l2 = l2; if(t_l1 -> val < t_l2 -> val) { root = t_l1; last = t_l1; t_l1 = t_l1 -> next; } else { root = t_l2; last = t_l2; t_l2 = t_l2 -> next; } while(true) { if(t_l1 == NULL) { if(t_l2 == NULL) { break; } else { last -> next = t_l2; break; } } else { if(t_l2 == NULL) { last -> next = t_l1; break; } else { if(t_l1 -> val < t_l2 -> val) { last -> next = t_l1; last = t_l1; t_l1 = t_l1 -> next; } else { last -> next = t_l2; last = t_l2; t_l2 = t_l2 -> next; } } } } return root; } };