慢慢把三四月份的每日一题用博客记录下来
算法思想
新建一个头结点,然后两个指针分别扫描两个链表,采用尾插法插到有序结果链表之后,最后返回head->next即可;
/**
* 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* head = new ListNode(0);
ListNode* end = head;
while(l1 && l2){
if(l1->val < l2->val){
end->next = l1;
end = end->next;
l1 = l1->next;
}else{
end->next = l2;
end = end->next;
l2 = l2->next;
}
}
if(l1) end->next = l1;
else end->next = l2;
return head->next;
}
};
2020年5月1日留