Title:Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
struct ListNode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; ListNode *mergetwolists (ListNode *l1, ListNode *l2) {if (L2 = = null) return l1;if (L1 = null) return l2; ListNode *r, *head;head = null;if (l1->val <= l2->val) //The first node of the list is small and the head pointer points to which node {head = L1;L1 = l1-> Next;} Else{head = L2;l2 = L2->next;} R = Head;while (L1&&L2) //Compare size {if (l1->val <= l2->val) {r->next = L1;L1 = L1->next;} Else{r->next = L2;l2 = L2->next;} R = R->next;} if (L1 = = null) //l1 is empty, direct connection l2{r->next = L2;} if (L2 = = null) //l2 is empty, direct connection l1{r->next = L1;} return head;}
"Leetcode OJ" Merge, Sorted Lists