方案一:将两个链表分别转换为两个列表,从列表的尾部开始对比两个列表的节点是否相等,并进行相应操作
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
wei_A = []
while headA:
wei_A.append(headA)
headA=headA.next
wei_A = wei_A[::-1]
wei_B = []
while headB:
wei_B.append(headB)
headB = headB.next
wei_B = wei_B[::-1]
count = -1
lA = len(wei_A)
lB = len(wei_B)
if lA < lB:
copy = wei_B
wei_B = wei_A
wei_A = copy
lA,lB=lB,lA
for i in range(lB):
if wei_A[i] == wei_B[i]:
count+=1
else:
break
if count != -1:
return wei_A[count]
else:
return None
#一种比较巧妙的方式是,分别为链表A和链表B设置指针A和指针B,然后开始遍历链表,如果遍历完当前链表,则将指针指向另外一个链表的头部继续遍历,直至两个指针相遇。
#最终两个指针分别走过的路径为:
#指针A :a+c+b
#指针B :b+c+a
#明显 a+c+b = b+c+a,因而如果两个链表相交,则指针A和指针B必定在相交结点相遇。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
nodeA = headA
nodeB = headB
while(nodeA !=nodeB):
nodeA = nodeA.next if nodeA else headB
nodeB = nodeB.next if nodeB else headA
return nodeA
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
seen = set()
p = headA
while p:
seen.add(p)
p = p.next
p = headB
while p:
if p in seen:
return p
p = p.next
return None