标签:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
python code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if not headA or not headB: #边界条件判定
return None
else:
p={}
i=headA
while i: #遍历其中一个列表,得到一个dict(hash table)
p[i.val]=1
i=i.next
i=headB
while i:
if i.val in p: #遍历另一个列表,如果某个元素在上面得到的dict中,则返回此元素
return i
else:
i=i.next
return None
other solutions given by leetcode:
There are many solutions to this problem:
For each node ai in list A, traverse the entire list B and check if any node in list B coincides with ai.
Traverse list A and store the address / reference to each node in a hash set. Then check every node bi in list B: if bi appears in the hash set, then bi is the intersection node.
Analysis written by @stellari.
leetcode Intersection of Two Linked Lists python
标签:
原文地址:http://www.cnblogs.com/bthl/p/4574517.html