Reputation: 51
This is a leetcode question 160. intersection of two linked list, where Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. https://leetcode.com/problems/intersection-of-two-linked-lists/
if map[headB]==1 is giving a runtime error in Leetcode. I know if i use 'if headB in map' it works fine, but i want to know why 'if map[headB]==1' gives error. Thank you.
# 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]:
map=dict()
while (headA):
map[headA]=1
headA=headA.next
while (headB):
if map[headB]==1: #why this doesn't work? ('if headB in map' works fine)
return headB
headB=headB.next
return None
Upvotes: 1
Views: 183
Reputation: 36
Because if key headB doesn't exist in map, map[headB] will throw a KeyError. It cannot compare something that doesn't exist to one.
Also, you might want to use some other name than just "map", because it shadows the built-in Python function map().
Upvotes: 1