Merge Two Sorted Lists
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. ListNode* newhead = new ListNode(0); ListNode* newlast = newhead; auto push = [&] (ListNode* node){ newlast->next = node; newlast = node; }; ListNode* il1 = l1; ListNode* il2 = l2; while(il1 != nullptr && il2 != nullptr) { if (il1->val > il2->val) { push(il2); il2 = il2->next; } else { push(il1); il1 = il1->next; } } if (il1 == nullptr) newlast->next = il2; else newlast->next = il1; newlast = newhead->next; delete newhead; return newlast; } };