21.Merge Two Sorted Lists
程序员文章站
2022-03-15 20:35:53
...
题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
分析:合并已排序的链表。
方法一:递归求解
/**
* 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) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l2->next,l1);
return l2;
}
}
};
方法二:新建一个链表,比较两个链表中元素的大小,把较小的那个链表赋值到新链表中,当其中一个链表空后,将剩下的链接直接接到新链表之后。
/**
* 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 *dummy = new ListNode(-1);
ListNode *cur=dummy;
while(l1 && l2)
{
if(l1->val < l2->val)
{
cur->next=l1;
l1=l1->next;
}
else
{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
cur->next=l1?l1:l2;
return dummy->next;
}
};
ListNode *dummy = new ListNode(-1);//创建新元素,开辟内存,因为构造函数 ListNode(int x) : val(x), next(NULL) {}
ListNode *cur=dummy;//最后的结果cur指向dummy,这样可以获取dummy所接收的全部元素,而dummy的指针由于每次都往下移,所以每次都更新
方法三:理解简单一点,一个移动指针和一个返回指针。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
ListNode *res=new ListNode(0);
if(l1->val < l2->val)
{
res=l1;
l1=l1->next;
}
else
{
res=l2;
l2=l2->next;
}
ListNode *head=res;
while(l1 && l2)
{
if(l1->val <= l2->val)
{
head->next=l1;
head=head->next;
l1=l1->next;
}
else
{
head->next=l2;
head=head->next;
l2=l2->next;
}
}
head->next=l1?l1:l2;
return res;
}
};
上一篇: 别打你家金毛了
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
167. Two Sum II - Input array is sorted [medium] (Python)
-
LeetCode C++ 599. Minimum Index Sum of Two Lists【Hash Table】简单
-
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
-
[LeetCode]Merge Two Sorted Lists(Python)
-
【LeetCode】4. Median of Two Sorted Arrays
-
1.Merge Two Sorted Arrays. py/合并排序有序数列
-
LeetCode 4. 两个排序数组的中位数 Median of Two Sorted Arrays
-
算法练习(3):Median of Two Sorted Arrays
-
LeetCode算法系列:4、Median of Two Sorted Arrays