码迷,mamicode.com
首页 > 其他好文 > 详细

3. Intersection of Two Linked Lists

时间:2014-12-30 20:30:42      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Notes:

    • If the two linked lists have no intersection at all, return null.
    • The linked lists must retain their original structure after the function returns.
    • You may assume there are no cycles anywhere in the entire linked structure.
    • Your code should preferably run in O(n) time and use only O(1) memory.

 

解法思路:

1. 先遍历List A 和 List B,  分别得到List A和List B的长度

2. 用长的list 减去短的List,e.g. x = |A - B|, 然后遍历长的List到X

3. 分别用2个指针指向2个List, 再进行判断即可

class Solution:
# @param two ListNodes
# @return the intersected ListNode
  def getIntersectionNode(self, headA, headB):
    temp = None

    temp = headA
    a = 0
    while temp != None:
      a += 1
      temp = temp.next

    b = 0
    temp = headB
    while temp != None:
      b += 1
      temp = temp.next

    x = 0
    temp1 = None
    if a > b:
      x = a - b
      temp = headA
      for i in range(x):
        temp = temp.next
      temp1 = headB
    else:
      x = b - a
      temp = headB
      for i in range(x):
        temp = temp.next
      temp1 = headA

    flag = False
    while temp != None and temp1 != None:
      if temp == temp1:
        flag = True
        break
      else:
        flag = False
        temp = temp.next
        temp1 = temp1.next

    if flag:
      return temp
    else:
      return None

 

3. Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/hechengzhu/p/4194302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!