作者:隐身勇者_641 | 来源:互联网 | 2023-09-25 11:42
方法一:***Definitionforsingly-linkedlist.*structListNode{*intval;*ListNode*next;*ListN
方法一:
/*** 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) {ListNode* p1&#61;l1;ListNode* p2&#61;l2;if(l1&#61;&#61;NULL){return l2;}else if(l2&#61;&#61;NULL){return l1;}ListNode* cur&#61;(l1->val<&#61;l2->val?l1:l2);ListNode* head&#61;cur;if(l1->val<&#61;l2->val){p1&#61;p1->next;}else{p2&#61;p2->next;}while(p1&&p2){if(p1->val<&#61;p2->val){cur->next&#61;p1;p1&#61;p1->next;}else{cur->next&#61;p2;p2&#61;p2->next;}cur&#61;cur->next;}while (p1){cur->next &#61; p1;p1 &#61; p1->next; cur &#61; cur->next;}while (p2){cur->next &#61; p2;p2 &#61; p2->next;cur &#61; cur->next;}return head;}
};
方法二&#xff1a;递归
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if (l1 &#61;&#61; NULL) return l2;if (l2 &#61;&#61; NULL) return l1;if (l1->val <&#61; l2->val) {l1->next &#61; mergeTwoLists(l1->next, l2);return l1;} else {l2->next &#61; mergeTwoLists(l1, l2->next);return l2;}
}