题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解法一:递归(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 and l2:
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
备注: 在 Python 中,and 和 or 都有提前截至运算的功能。
and:如果 and 前面的表达式已经为 False,那么 and 之后的表达式将被 跳过,返回左表达式结果
or:如果 or 前面的表达式已经为 True,那么 or 之后的表达式将被跳过,直接返回左表达式的结果
例子:[] and 7 等于 []
时间复杂度:
解法二:迭代(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 newhead(0);
ListNode *p = &newhead;
while(l1&&l2)
{
if(l1->val > l2->val) swap(l1, l2);
p->next = l1;
l1 = l1->next;
p = p->next;
}
p->next = l1?l1:l2;
return newhead.next;
}
};