Topic
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.
Analysis
Don't forget to first determine whether the list of two lists is empty. The rest can be implemented using both recursive and non-recursive methods.
Code
Recursive mode:
Class Solution {public: listnode* mergetwolists (listnode* L1, listnode* L2) { listnode* mergedlist = NULL; if (L1 = = NULL) return L2; if (L2 = = NULL) return L1; if (L1->val < L2->val) { mergedlist = L1; Mergedlist->next = mergetwolists (L1->next, L2); } else { mergedlist = L2; Mergedlist->next = mergetwolists (L1, L2->next); } return mergedlist;} ;
Non-recursive mode:
Class Solution {public:listnode* mergetwolists (listnode* L1, listnode* L2) {listnode* mergedlist = NULL; if (L1 = = NULL) return l2; if (L2 = = NULL) return L1; if (L1->val < l2->val) {mergedlist = L1; Mergedlist->next = NULL; L1 = l1->next; } else {mergedlist = L2; Mergedlist->next = NULL; L2 = l2->next; } listnode* p = mergedlist; while (L1 = null && L2! = null) {if (L1->val < l2->val) {p-& Gt;next = L1; L1 = l1->next; p = p->next; P->next = NULL; } else {p->next = L2; L2 = l2->next; p = p->next; P->next = NULL; }} if (L1!)= NULL) P->next = L1; else if (L2! = NULL) P->next = L2; return mergedlist; }};
Merge Sorted lists--Problem Solving report