标签:
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:
null
.
解法思路:
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