在线美食网站开发论文/seo优化服务
【题目】
给定两个有序单链表的头节点head1和head2,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头节点。
【思路】
选择小的head作为头结点,然后将另一个链表的所有节点并入head较小的链表中即可
【python】
def merge(head1,head2):if head1 == None: return head2if head2 == None:return head1head == head1 if head1.val < head2 else head2cur1 = head1 if head == head1 else head2cur2 = head1 if head == head2 else head1pre = Nonenext = Nonewhile cur1 != None and cur2 != None:if cur1.val <= cur2.val:pre = cur1cur1 = cur1.nextelse:next = cur2.nextpre.next = cur2cur2.next = cur1pre = cur2cur2 = nextpre.next = cur1 if cur2 == None else cur2return head
【另一个题目】
合并两个已排序的链表,并将其作为一个新列表返回。新列表应该通过拼接前两个列表的节点来完成。
例如:输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
【python】
def merge(L1,L2):dummy = ListNode(0)s = dummywhile l1 and l2:if l1.val > l2.val:s.next = l2l2 = l2.nextelse:s.next = l1l1 = l1.nextif l1:while l1:s.next = l1if l2:while l2:s.next = l2return dummy.next