地址:点击打开链接
求两个链表的交集节点,用双指针来遍历
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
本文介绍了一种使用双指针的方法来找到两个链表的交集节点。通过调整两个指针的起始位置,确保它们从较短的链表开始遍历时能同时到达交集点,从而高效地解决问题。
800

被折叠的 条评论
为什么被折叠?



