[关闭]
@Scrazy 2017-04-11T10:01:01.000000Z 字数 586 阅读 901

求两个链表的第一个交点

python 算法

思路:
1. 求出两个链表的长度
2. 长的链表先走两步,直至俩链表一样长
3. 依次比较俩链表的每一个值
4. 相同,直接 return 否则,return None


  1. # -*- coding:utf-8 -*-
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def FindFirstCommonNode(self, pHead1, pHead2):
  8. if not pHead1 and pHead2:
  9. return None
  10. head1 = pHead1
  11. head2 = pHead2
  12. length1 = length2 = 0
  13. while pHead1:
  14. pHead1 = pHead1.next
  15. length1 += 1
  16. while pHead2:
  17. pHead2 = pHead2.next
  18. length2 += 1
  19. if length1 > length2:
  20. while length1 - length2:
  21. head1 = head1.next
  22. length1 -= 1
  23. else:
  24. while length2 - length1:
  25. head2 = head2.next
  26. length2 -= 1
  27. while head1 and head2:
  28. if head1 is head2:
  29. return head1
  30. head1 = head1.next
  31. head2 = head2.next
  32. return None
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注