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.
Ideas. First of all, if there is an empty list, if there is, then directly return to another linked list, if not, then start comparing the current node of the two linked list, return the smaller elements as precursors, and the pointer moves backward one bit, and then compare, so loop, know that a list of the next point of the list of elements to connect.
Iteration:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *mergetwolists (ListNode *l1, ListNode *l2) { if (L1 = = NULL) return l2; if (L2 = = NULL) return L1; if (L1->val < L2->val) { L1->next = mergetwolists (L1->next, L2); return L1; } else { L2->next = mergetwolists (L2->next, L1); return l2;}} ;
Cycle:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(L1==null)returnL2; if(L2==null)returnL1; ListNode* head = (L1->val > L2->val)?l2:l1; ListNode*temp; while(L1!=null && l2!=NULL) { while(l1->next!=null&&l2!= NULL &&l1->next->val <= l2->val) {L1= l1->Next; } if(L1! = null&&l2!=null &&l1->val <= l2->val) {Temp= l1->Next; L1->next =L2; L1=temp; } while(L2->next!=null&& L1!=null &&l2->next->val <= l1->val) {L2= l2->Next; } if(L2! = NULL &&l1! = Null&&l2->val <= l1->val) {Temp= l2->Next; L2->next =L1; L2=temp; } } returnHead; }};
Leetcode "21. Merge Sorted Lists "