1. 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
方法一:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getIntersectionNode(headA, headB):
A, B = headA, headB
while A!= B:
A = A.next if A else headB
B = B.next if B else headA
return A
方法二:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getIntersectionNode(headA, headB):
seen = set()
while headA:
seen.add(headA)
headA = headA.next
while headB:
if headB in seen:
return headB
headB = headB.next
return None
方法三:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def getLength(head):
length = 0
while head:
length += 1
head = head.next
return length
def getIntersectionNode(headA, headB):
lenA = getLength(headA)
lenB = getLength(headB)
if lenA > lenB:
for _ in range(lenA - lenB):
headA = headA.next
elif lenB > lenA:
for _ in range(lenB - lenA):
headB = headB.next
while headA and headB:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None