第三天leetcode刷题
解题思路:首先这两个链表是排序好的,那么我们先定义一个空链表,再定义两个指针 i,j,按照顺序比较两个链表,如果 i 指向的数字小于 j指向的数字,i 指向的节点插入新链表中,i = i -> next,反之则操作 j。不过要注意其中一个链表可能会先结束,所以另一个未结束的链表直接插入新链表即可
具体代码实现如下:
/**
* 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* h1 = l1;
ListNode* h2 = l2;
ListNode* t = new ListNode(0);
ListNode* curr = t;
while (h1 && h2)
{
if (h1->val <= h2->val) {
curr->next = h1;
h1 = h1->next;
}
else{
curr->next = h2;
h2 = h2->next;
}
curr = curr->next;
}
while (h1)
{
curr->next = h1;
h1 = h1->next;
curr = curr->next;
}
while(h2)
{
curr->next = h2;
h2 = h2->next;
curr = curr->next;
}
ListNode* res = t->next;
delete t;
return res;
}
};
时间复杂度: O(N + M);空间复杂度: O(1)