原题目
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
思路
边界情况:l1、l2都为空,返回空;其中一个为空,返回另一个。
新建一个头结点,当两个链表都不为空时遍历l1和l2,将值较小结点的那个插入到头结点的后面,然后较小节点指针后移。当有一个链表为空时,新建链表的最后一个结点指向非空链表。
第一遍解法
# Runtime: 40 ms, faster than 97.35% of Python3 O(min(m,n))
# Memory Usage: 13.1 MB, less than 68.52% of Python3 S(m+n)
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
l3 = ListNode(0)
p = l3
while l1 and l2:
if l1.val <= l2.val:
p.next, p, l1 = l1, l1, l1.next
p.next = None
else:
p.next, p, l2 = l2, l2, l2.next
p.next = None
if l1:
p.next = l1
if l2:
p.next = l2
return l3.next # 去掉无效头结点
网上好的解法
//递归
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(l1, l2.next);
return l2;
}
}
# 迭代
def mergeTwoLists1(self, l1, l2):
dummy = cur = ListNode(0)
while l1 and 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 or l2
return dummy.next
自己可以改进的地方
# 连续赋值等于
p = l3 = ListNode(0)
# 无论添加哪条链表的结点新链表的指针都要指向后一个
cur.next = l1
cur.next = l2
cur = cur.next
# 指向不为空的链表结点的语句
cur.next = l1 or l2
最简代码