当前位置: 代码迷 >> 综合 >> [LeetCode21]Merge Two Sorted Lists(合并两个有序链表)
  详细解决方案

[LeetCode21]Merge Two Sorted Lists(合并两个有序链表)

热度:67   发布时间:2023-12-06 19:19:45.0
/*** 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(NULL==l1) return l2;if(NULL==l2) return l1;ListNode *dummy=new ListNode(-1), *cur=dummy;while(l1!=NULL&&l2!=NULL){if(l1->val<l2->val){cur->next=l1;l1=l1->next;}else{cur->next=l2;l2=l2->next;}cur=cur->next;}if(l1) cur->next=l1;if(l2) cur->next=l2;return dummy->next;}
};

  相关解决方案