标签:problem lse ini val lin alt img init .com
目录
Merge Two Sorted Lists - LeetCode
解法一:先比较两个链表长度一致的部分,多余的部分直接加进答案链表即可。时间复杂度为O(n)
/**
* 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* ans = new ListNode(0);
ListNode* pointer = ans;
while(l1 != NULL && l2 != NULL)
{
if(l1->val < l2->val)
{
pointer->next = new ListNode(l1->val);
pointer = pointer->next;
l1 = l1->next;
}
else
{
pointer->next = new ListNode(l2->val);
pointer = pointer->next;
l2 = l2->next;
}
}
while(l1 != NULL)
{
pointer->next = new ListNode(l1->val);
pointer = pointer->next;
l1 = l1->next;
}
while(l2 != NULL)
{
pointer->next = new ListNode(l2->val);
pointer = pointer->next;
l2 = l2->next;
}
return ans->next;
}
};
Merge Two Sorted Lists - LeetCode
标签:problem lse ini val lin alt img init .com
原文地址:https://www.cnblogs.com/multhree/p/10337671.html