leetcode Intersection of Two Linked Lists python

时间:2015-06-14 06:56:50   收藏:0   阅读:438

Intersection of Two Linked Lists

 

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:

Analysis written by @stellari.

 

原文:http://www.cnblogs.com/bthl/p/4574517.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!