题意:

image.png
解题思路:

  1. 思路:
  2. * [Hash]
  3. * 同时移动两个链表,链表到达尾部,则指向另外一个链表头部,继续遍历,这样会抵消长度差;
  4. * 如果没有相交,则代表长度相等,最后会是 nil == nil,反之有相交;

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode $headA
  12. * @param ListNode $headB
  13. * @return ListNode
  14. */
  15. function getIntersectionNode($headA, $headB) {
  16. if ($headA === null || $headB === null) {
  17. return null;
  18. }
  19. $curA = $headA;
  20. $curB = $headB;
  21. while ($curA !== $curB) {
  22. $curA = ($curA === null) ? $headB : $curA->next;
  23. $curB = ($curB === null) ? $headA : $curB->next;
  24. }
  25. return $curA;
  26. }
  27. function getIntersectionNodeHash($headA, $headB) {
  28. $curA = $headA;
  29. $curB = $headB;
  30. $map = [];
  31. while ($curA != null) {
  32. array_push($map, $curA);
  33. $curA = $curA->next;
  34. }
  35. while ($curB != null) {
  36. if (in_array($curB, $map, true)) {
  37. return $curB;
  38. }
  39. $curB = $curB->next;
  40. }
  41. return null;
  42. }
  43. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func getIntersectionNode(headA, headB *ListNode) *ListNode {
  9. curA,curB := headA,headB
  10. for curA != curB {
  11. if curA == nil {
  12. curA = headB
  13. } else {
  14. curA = curA.Next
  15. }
  16. if curB == nil {
  17. curB = headA
  18. } else {
  19. curB = curB.Next
  20. }
  21. }
  22. return curA
  23. }