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.
这题就是说判断两个链表是否有公共节点,如果有,返回第一个公共节点。
分析:如果两条链表有公共节点,则这个条链表的最后一个节点一定相同,这应该是解题的关键。所以第一步就是首先判断链表有没有公共点,其二,如果链表有公共点,则该点之后的两条链表长度一定相同,所以第二部就是先让较长的链表先走abs(lenA - lenB)步,这样一来,开始判断的部分长度一定相等。
- class ListNode:
- def __init__(self, x):
- self.val = x
- self.next = None
-
- class Solution:
-
-
- def getIntersectionNode(self, headA, headB):
- lastA = headA
- lastB = headB
- lenA = 0
- lenB = 0
- if None == headA or None == headB:
- return None
- while lastA.next != None:
- lastA = lastA.next
- lenA += 1
-
- while lastB.next != None:
- lastB = lastB.next
- lenB += 1
- if lastA != lastB:
- return None
-
- p = headA
- q = headB
- for i in xrange(lenA - lenB):
- p = p.next
- for i in xrange(lenB - lenA):
- q = q.next
-
- while p != None:
- if p == q:
- return p;
- p = p.next
- q = q.next
- return None
-
- sol = Solution()
- a1 = ListNode(0)
- a2 = ListNode(1)
- a3 = ListNode(2)
- a4 = ListNode(33)
-
- b1 = ListNode(8)
- b2 = ListNode(6)
-
- a1.next = a2
- a2.next = a3
- a3.next = a4
-
- b1.next = b2
- b2.next = a3
-
- node = sol.getIntersectionNode(a1, b1)
- while node != None:
- print("%d" % node.val)
- node = node.next