博文中会简要介绍Leetcode P0021题目分析及解题思路。
“Merge Two Sorted Lists”是一道使用优先级队列(堆)的题的简化版。本题无需使用优先级队列,但是后续它的原型题p0023会使用优先级队列来解题。
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
这道题的思路相对比较简单。控制时间复杂度在O(n)以内即可,采用的方法是穿插比较,即l1
链表和l2
链表上的结点依次比较,若l1
的结点较小,则将其连在新链表的末尾,并且移动l1
,反之亦然。整个解法看起来像两个线相互缠绕,所以顾名思义是穿插比较。
以下是Java的题解代码实现。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null)
return (l1 == null)? l2: l1;
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (l1 != null || l2 != null) {
if (l1 == null) {
tail.next = l2;
break;
}
else if (l2 == null) {
tail.next = l1;
break;
}
else {
if (l2.val > l1.val) {
tail.next = l1;
l1 = l1.next;
}
else {
tail.next = l2;
l2 = l2.next;
}
}
tail = tail.next;
}
return dummy.next;
}
}
以下是C++的题解代码实现。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL || l2 == NULL)
return l1? l1: l2;
ListNode *dummy = new ListNode(0);
ListNode *tail = dummy;
while (l1 != NULL || l2 != NULL) {
if (l1 == NULL) {
tail->next = l2;
break;
}
else if (l2 == NULL) {
tail->next = l1;
break;
}
else {
if (l2->val > l1->val) {
tail->next = l1;
l1 = l1->next;
}
else {
tail->next = l2;
l2 = l2->next;
}
}
tail = tail->next;
}
return dummy->next;
}
};