题目

面试题02.07
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
image.png

思路

求两个链表交点节点的指针,要注意,交点不是数值相等,而是指针相等(指针指向同一地址)

两个链表从某一位置开始到末尾完全相同,如果两个链表长度不一致,那么较长的链表前面多出来的部分一定是多余的。所以可以先将多部部分去掉,问题就变成了两个等长链表同时遍历找相同指针的问题
求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置。
image.png

  1. class Solution
  2. {
  3. public:
  4. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
  5. {
  6. //求两个链表的长度
  7. int sizeA = 0, sizeB = 0;
  8. ListNode *nodeA = headA, *nodeB = headB;
  9. while (nodeA != nullptr)
  10. {
  11. sizeA++;
  12. nodeA = nodeA->next;
  13. }
  14. while (nodeB != nullptr)
  15. {
  16. sizeB++;
  17. nodeB = nodeB->next;
  18. }
  19. nodeA = headA;
  20. nodeB = headB;
  21. //长度较长的链表移动 gap 步,使两链表尾部对齐
  22. int gap = sizeA - sizeB;
  23. if (sizeA > sizeB)
  24. {
  25. int gap = sizeA - sizeB;
  26. while (nodeA != nullptr && gap > 0)
  27. {
  28. nodeA = nodeA->next;
  29. gap--;
  30. }
  31. }
  32. else
  33. {
  34. int gap = sizeB - sizeA;
  35. while (nodeB != nullptr && gap > 0)
  36. {
  37. nodeB = nodeB->next;
  38. gap--;
  39. }
  40. }
  41. //长度较长的链表移动 gap 步,使两链表尾部对其
  42. while (nodeA != nullptr)
  43. {
  44. if (nodeA == nodeB)
  45. return nodeA;
  46. nodeA = nodeA->next;
  47. nodeB = nodeB->next;
  48. }
  49. return nullptr;
  50. }
  51. };