Problem
Solution
If one list is longer than the other, ignore the leading part and start at the point where the total number of nodes will be the same.
Compare one by one, and if none of the nodes are equivalent, return null.
# 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
lengthA = -1
lengthB = -1
pA = headA
pB = headB
while pA:
lengthA += 1
pA = pA.next
while pB:
lengthB += 1
pB = pB.next
pB = headB
pA = headA
if lengthA > lengthB:
for _ in range(lengthA-lengthB):
pA = pA.next
else:
for _ in range(lengthB-lengthA):
pB = pB.next
while pA:
if pA == pB:
return pA
pA = pA.next
pB = pB.next
return None
Time Complexity
O(N)
Space Complexity
O(1)
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[Coderust] Swapping Nodes in a Linked List (0) | 2022.05.21 |
---|---|
[Coderust] Remove Nth Node From End of List (0) | 2022.05.18 |
[Coderust] Remove Duplicates from a Linked List (0) | 2022.03.10 |
[Coderust] Implementation of Linked List (0) | 2022.03.08 |
[Coderust] Merge an Array With Overlapping Intervals (0) | 2022.02.28 |