160.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. function ListNode(val) {
  9. this.val = val;
  10. this.next = null;
  11. }
  12. /**
  13. * @param {ListNode} headA
  14. * @param {ListNode} headB
  15. * @return {ListNode}
  16. */
  17. var getIntersectionNode = function(headA, headB) {
  18. let set = new Set()
  19. let pA = headA, pB = headB
  20. while (pA !== null && pB != null) {
  21. if (set.has(pA)) return pA
  22. set.add(pA)
  23. if (set.has(pB)) return pB
  24. set.add(pB)
  25. pA = pA.next
  26. pB = pB.next
  27. }
  28. if (pA === pB) return null
  29. let curr = null
  30. if (pA === null) {
  31. curr = pB
  32. } else {
  33. curr = pA
  34. }
  35. while (curr !== null) {
  36. if (set.has(curr)) return curr
  37. set.add(curr)
  38. curr = curr.next
  39. }
  40. return null
  41. };
  42. function __main__() {
  43. let n2 = new ListNode(2)
  44. let n22 = new ListNode(3)
  45. let n23 = new ListNode(3)
  46. let n24 = new ListNode(3)
  47. n2.next = n22
  48. n22.next = n23
  49. n23.next = n24
  50. let n1 = new ListNode(3)
  51. let n12 = new ListNode(3)
  52. let n13 = new ListNode(3)
  53. n1.next = n12
  54. n12.next = n13
  55. n24.next = n12
  56. let n3 = new ListNode(3)
  57. console.log(getIntersectionNode(n1, n2))
  58. console.log(getIntersectionNode(n2, n3))
  59. }
  60. __main__()