Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
## Two pointer
## To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pBpB would reach the end of the merged list first, because pBpB traverses exactly 2 nodes less than pApA does. By redirecting pBpB to head A, and pApA to head B, we now ask pBpB to travel exactly 2 more nodes than pApA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
if headA == None or headB == None:
return None
A_pointer = headA
B_pointer = headB
while A_pointer is not B_pointer: ## stopping critera is either they are at None or at the intersection
if A_pointer == None:
A_pointer = headB
else:
A_pointer = A_pointer.next
if B_pointer == None:
B_pointer = headA
else:
B_pointer = B_pointer.next
return A_pointer
## First Node
## Brute Force
nodeA = headA
nodeB = headB
while nodeA is not None:
while nodeB is not None:
if nodeA == nodeB:
return nodeA
nodeB = headB.next
nodeA = headA.next
return None
## Second approach
#设置hash table,用set
hashTable = set()
#put all headA nodes into set
while headA is not None:
hashTable.add(headA)
headA = headA.next
#check each node in headB if they are in hashTable set
while headB is not None:
# if they are in hashTable set, then they have intersection node and return.
if headB in hashTable:
return headB
# if not, check next node in headB linked list.
else:
headB = headB.next
# if headA and headB all became None and no intersection is found, then return None
return None
```