/**
* 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;
}
};
[LeetCode21]Merge Two Sorted Lists(合并两个有序链表)
最新推荐文章于 2024-08-10 23:27:32 发布