面试题 02.07. 链表相交 - 力扣(LeetCode)
思路:先让长的链表指针往后走,走到剩余和短的链表的长度一样时停止,然后开始比较两个指针指向的节点是否相等。
class Solution(object):
def getIntersectionNode(self, headA, headB):
tail1=ListNode(0,headA)
m=0
tail2=ListNode(0,headB)
n=0
while tail1.next:
tail1=tail1.next
m+=1
while tail2.next:
tail2=tail2.next
n+=1
if m<=n:
sub=n-m
for i in range(sub):
headB=headB.next
while headA and headB and headA is not headB:
headA=headA.next
headB=headB.next
return headA
else:
sub = m-n
for i in range(sub):
headA=headA.next
while headA and headB and headA is not headB:
headA=headA.next
headB=headB.next
return headA
注意:是节点相等而不是节点的值相等!