地址:点击打开链接
求两个链表的交集节点,用双指针来遍历
ps:这道题是微软的一道题,当年微软也考过,时光飞逝啊....
答案:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None:
return headA
if headB == None:
return headB
lengthA = self.getLength(headA)
lengthB = self.getLength(headB)
a = headA
b = headB
if lengthA >= lengthB:
n = lengthA - lengthB
while n:
a = a.next
n -= 1
else:
n = lengthB - lengthA
while n:
b = b.next
n -= 1
while a != b:
a = a.next
b = b.next
return a
def getLength(self,listNode):
p = listNode
length = 0
while p:
length += 1
p = p.next
return length