21. Merge Two Sorted Lists

xiaoxiao2021-02-28  48

解法一

class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* newLis=new ListNode(-1),*cur=newLis; while(l1&&l2){ if(l1->val>l2->val){ newLis->next=new ListNode(l2->val); l2=l2->next; }else{ newLis->next=new ListNode(l1->val); l1=l1->next; } newLis=newLis->next; } newLis->next=(l1==NULL)?l2:l1; return cur->next; } };

(l1==NULL)?l2:l1和l1?l2:l1有何区别 解法二:递归的写法

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1) return l2; if(!l2) return l1; if(l1->val<l2->val){ l1->next=mergeTwoLists(l1->next,l2); return l1; }else{ l2->next=mergeTwoLists(l1,l2->next); return l2; } }

另一种递归写法

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1) return l2; if(!l2) return l1; ListNode* head=l1->val<l2->val?l1:l2; ListNode* nonHead=l1->val<l2->val?l2:l1; head->next=mergeTwoLists(head->next,nonHead); return head; }

解法四

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1||(l2&&l1->val>l2->val)) swap(l1,l2); if(l1) l1->next=mergeTwoLists(l1->next,l2); return l1; }
转载请注明原文地址: https://www.6miu.com/read-1450266.html

最新回复(0)