leetcode每日一题-21:合并两个有序链表
链接
题目
分析
我们设置一个虚拟头节点和新链表的尾节点,然后一直遍历两个链表,往新链表尾节点后面插入即可。
代码
C++
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
auto dummy = new ListNode(1);
auto tail = dummy;
while(list1 and list2)
{
if(list1->val <= list2->val)
{
tail->next = list1;
tail = tail->next;
list1 = list1->next;
}
else
{
tail->next = list2;
tail = tail->next;
list2 = list2->next;
}
}
while(list1)
{
tail->next = list1;
tail = tail->next;
list1 = list1->next;
}
while(list2)
{
tail->next = list2;
tail = tail->next;
list2 = list2->next;
}
tail->next = nullptr;
return dummy->next;
}
};
Java
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1);
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
prev.next = l1 == null ? l2 : l1;
return prehead.next;
}
}
作者:LeetCode-Solution
|