两个链表交集
程序员文章站
2022-07-13 17:51:53
...
题目给定两个链表,两个链表有一部分是一样,求给出两个链表交集开始的地方。
方法1
步骤1 ,求先求出两个链表的长度差,然后让
步骤2,长度较长的链表,向后移动长度差。使得两个链表后续遍历长度相同,
步骤3 ,最后移动两个指针,一次对比数据,
def getIntersectionNode(headA,headB):
curA,curB = headA,headB
lenA,lenB = 0,0
while curA is not None:
lenA += 1
curA = curA.next
while curB is not None:
lenB += 1
curB = curB.next
curA,curB = headA,headB
if lenA > lenB:
for i in range(lenA-lenB):
curA = curA.next
elif lenB > lenA:
for i in range(lenB - lenA):
curB = curB.next
while curB != curA:
curB = curB.next
curA = curA.next
return curA
方法2 ,将两个链表相互补齐,然后遍历,
def getIntersectionNode2(headA,headB):
if headA and headB:
A,B = headA,headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A