【题目】
给定两个有序单链表的头节点head1和head2,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头节点。
【思路】
选择小的head作为头结点,然后将另一个链表的所有节点并入head较小的链表中即可
【python】
def merge(head1,head2):
if head1 == None:
return head2
if head2 == None:
return head1
head == head1 if head1.val < head2 else head2
cur1 = head1 if head == head1 else head2
cur2 = head1 if head == head2 else head1
pre = None
next = None
while cur1 != None and cur2 != None:
if cur1.val <= cur2.val:
pre = cur1
cur1 = cur1.next
else:
next = cur2.next
pre.next = cur2
cur2.next = cur1
pre = cur2
cur2 = next
pre.next = cur1 if cur2 == None else cur2
return head
【另一个题目】
合并两个已排序的链表,并将其作为一个新列表返回。新列表应该通过拼接前两个列表的节点来完成。
例如:输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
【python】
def merge(L1,L2):
dummy = ListNode(0)
s = dummy
while l1 and l2:
if l1.val > l2.val:
s.next = l2
l2 = l2.next
else:
s.next = l1
l1 = l1.next
if l1:
while l1:
s.next = l1
if l2:
while l2:
s.next = l2
return dummy.next