First two single-linked lists are ordered
When merging two single-linked lists, it can be cumbersome to think about adding or subtracting a sequence.
It is important to open a serial header to store it, not necessarily to open up memory, mainly a concept
In fact, the merge of method sense and merge algorithm is a concept
/** * 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) {if (L1 = = NULL) { return L2; } else if (L2 = = NULL) {return L1; } ListNode *head = NULL; if (L1->val < l2->val) {head = L1; L1 = l1->next; } else {head = L2; L2 = l2->next; } ListNode *phead = head; while (L1 && L2) {if (L1->val < l2->val) {head->next = L1; Head = head->next; L1 = l1->next; } else {head->next = L2; Head = head->next; L2 = l2->next; }} if (L1){head->next = L1; } if (L2) {head->next = L2; } return phead; }};
Provide a solution to the recursion on the offer of the sword
/** * 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; } else if (L2 = = NULL) { return L1; } ListNode *head = NULL; if (L1->val < L2->val) { head = L1; Head->next = Mergetwolists (L1->NEXT,L2); } else { head = L2; Head->next = Mergetwolists (L1,l2->next); } return head; };
Leetcode-merge Two Sorted lists merge two ordered single-linked lists