21. 合并两个有序链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *mirror,*pre; mirror = new ListNode; pre = mirror; while(l1&&l2) { if(l1->val<l2->val) { pre->next = l1;//1->1 l1 = l1->next;//p1 = 2 } else { pre->next = l2;//0->1 l2 = l2->next;//p2 = 3 } pre = pre->next;//pre = 1 } pre->next = l1 == NULL ? l2 : l1; return mirror->next; delete(mirror); } };
原文:https://www.cnblogs.com/jessica216/p/13388080.html