-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0160-intersection-of-two-linked-lists.py
42 lines (34 loc) · 1.36 KB
/
0160-intersection-of-two-linked-lists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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) -> Optional[ListNode]:
if not headA or not headB:
return None
# Step 1: Initialize two pointers
pA, pB = headA, headB
# Step 2: Determine the lengths of A and B
lenA, lenB = 0, 0
while pA:
lenA += 1
pA = pA.next
while pB:
lenB += 1
pB = pB.next
# Reset pointers to head
pA, pB = headA, headB
# Step 3: Adjust the starting position of the pointers
while lenA > lenB:
pA = pA.next
lenA -= 1
while lenB > lenA:
pB = pB.next
lenB -= 1
# Step 4: Move both pointers until they meet
while pA != pB:
pA = pA.next
pB = pB.next
# Return either one of the pointers
return pA