两个链表相交的起始节点
class Solution(object):
def getIntersectionNode(self, headA, headB):
p1=headA #双指针 分别在两条链表上行走
p2=headB
while p1 != p2:
#指针先在自己的链表上遍历,遍历完遍历另一条链表
p1=p1.next if p1 else headB
p2=p2.next if p2 else headA
return p1 #指针相遇时即公共节点
合并两个有序链表
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
dummy=ListNode(0) #设置哑节点放在新链表之前,最后返回dummy.next
cur=dummy
while pHead1 and pHead2:
#判断两个链表的头结点谁更小,cur指向更小的结点
if pHead1.val <= pHead2.val:
cur.next=pHead1
pHead1=pHead1.next
cur=cur.next
else:
cur.next=pHead2
pHead2=pHead2.next
cur=cur.next
cur.next=pHead1 if pHead1 else pHead2 #拼接未对比的链表
return dummy.next
合并k个有序链表
解法一:在合并两个有序链表的基础上,按照顺序一一合并
class Solution:
def mergeKLists(self , lists ):
k=len(lists)
merged=None #目前的合并结果
for i in range(k): #按顺序一一合并
merged=self.merge2Lists(merged,lists[i])
return merged
def merge2Lists(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 if l1 else l2
return dummy.next
解法二:分治合并
class Solution(object):
def mergeKLists(self, lists):
k=len(lists)
interval=1 #配对的两个链表之间的间隔
if k==0:return None
while interval < k: #间隔大于或等于链表个数时合并完毕
for i in range(0,k-interval,interval*2):
#遍历的间隔为interval*2,下一个i为i+interval+interval
lists[i]=self.merge2Lists(lists[i], lists[i+interval])
interval *= 2 #一轮合并结束后间隔翻倍
return lists[0]
def merge2Lists(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 if l1 else l2
return dummy.next