21.Merge Two Sorted Lists [难度:简单]
【题目】
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
【解题C++】
这道题的题目不是很严谨,没有说明具体的排序情况,要是已知序列是从大到小......而且也不清楚那俩链表有没有头结点。
不过嘛不影响什么思路还是非常简单的~在两个链表均不为空的前提下,同时遍历俩链表,并比较大小。更小的那一个呢,加入新链表战队,并将新链表和更小值所在链表的指针往后挪一位。因此,在最开始的时候还得有一个结点指向新链表的头结点,以便最后的返回。最后退出循环后,别忘了俩链表可能长度不等,更长一点的链表这时候就可以直接接在新链表后头啦。
/**
* 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 *newL,*head;
// 注意题目的结构体定义,new新结点的时候别忘了给个初始值
newL = new ListNode(0);
head = newL;
while(l1&&l2)
{
if(l1->val<l2->val)
{
newL->next = l1;
l1 = l1->next;
}
else
{
newL->next = l2;
l2 = l2->next;
}
newL = newL->next;
}
if(l1) newL->next = l1;
if(l2) newL->next = l2;
return head->next;
}
};
【解题Python】
和C++的思路没差,只是语法不同,Python版本的就有递归来实现吧~
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
newL = None
if l1.val<=l2.val:
newL = l1
newL.next = self.mergeTwoLists(l1.next,l2)
else:
newL = l2
newL.next = self.mergeTwoLists(l1,l2.next)
return newL
博客围绕“Merge Two Sorted Lists”题目展开,指出题目存在不严谨之处,未说明排序情况和有无头结点。介绍了解题思路,在两链表不为空时同时遍历并比较大小,将小值加入新链表,最后处理长度不等的情况。还给出了C++和Python的解题方法。
1477

被折叠的 条评论
为什么被折叠?



