【leetcode❤python】 160. Intersection of Two Linked Lists
#-*- coding: UTF-8 -*-
#两种方法
#方法1:
#计算出A和B两个链表的长度分别为m、n;
#长度长的链表先走m-n步,之后再一次遍历寻找
#方法2:
#先走到一个链表的尾部,从尾部开始走;
#跳到另一个链表的头部
#如果相遇,则相遇点为重合节点
class Solution(object):
def getLinkLenth(self,head):
lenth=0
while head!=None:
lenth+=1
head=head.next
return lenth
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
# if headA==None or headB==None:return None
dummyA=ListNode(0)
dummyA.next=headA
dummyB=ListNode(0)
dummyB.next=headB
lenA=self.getLinkLenth(headA)
lenB=self.getLinkLenth(headB)
if lenA>lenB:
xlen=lenA-lenB
for i in xrange(xlen):
dummyA=dummyA.next
if lenB>lenA:
xlen=lenB-lenA
for i in xrange(xlen):
dummyB=dummyB.next
while dummyB.next and dummyA.next:
if dummyB.next==dummyA.next:
return dummyA.next
dummyB=dummyB.next
dummyA=dummyA.next
return None
# listA=[]
listB=[]
if headA==None or headB==None:return None
while headA:
listA.append(headA.val)
headA=headA.next
while headB:
listB.append(headB.val)
headB=headB.next
minlen=len(listA) if len(listA)<len(listB) else len(listB)
print listA,listB,minlen
if listA[-1]!=listB[-1]:return None
for i in xrange(1,minlen+1):
print i
if listA[-i]!=listB[-i]:
return ListNode(listA[-i+1])
if i==minlen:
return ListNode(listA[-i])