首页 > 代码库 > 3. Intersection of Two Linked Lists

3. 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.

 

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