当前位置:   article > 正文

面试题 02.07. 链表相交 python_相交链表 python

相交链表 python

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

图示两个链表在节点 c1 开始相交

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 。 

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
  8. curA = headA
  9. curB = headB
  10. sizeA = 0
  11. sizeB = 0
  12. while curA != None:
  13. sizeA += 1
  14. curA = curA.next
  15. while curB != None:
  16. sizeB += 1
  17. curB = curB.next
  18. curA = headA
  19. curB = headB
  20. if sizeA > sizeB:
  21. n = sizeA - sizeB
  22. while n:
  23. curA = curA.next
  24. n -= 1
  25. elif sizeA < sizeB:
  26. n = sizeB - sizeA
  27. while n:
  28. curB = curB.next
  29. n -= 1
  30. # while curA.val != curB.val and curA != None:
  31. # ❗注意是节点的相同而不是值的相同。因此不需要取val属性。否则:
  32. # 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5],
  33. # skipA = 2, skipB = 3
  34. # while里取val则输出:Intersected at '1'.正确输出:Intersected at '8'
  35. while curA != curB and curA != None:
  36. curA = curA.next
  37. curB = curB.next
  38. return curA

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/689901
推荐阅读
相关标签
  

闽ICP备14008679号