142.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict'
  2. /**
  3. * Definition for singly-linked list.
  4. * function ListNode(val) {
  5. * this.val = val;
  6. * this.next = null;
  7. * }
  8. */
  9. function ListNode(val) {
  10. this.val = val
  11. this.next = null
  12. }
  13. /**
  14. * @param {ListNode} head
  15. * @return {ListNode}
  16. */
  17. var detectCycle = function (head) {
  18. // Assume l1 = dis(head, entry), and l2 = dis(entry, meeting),
  19. // c = len(cycle), n = count of loop (fast pointer), then
  20. // dis(head, fast) = l1+l2+n*c = 2*dis(head, slow) = 2*(l1+l2).
  21. // So l1 = c-l2+(n-1)*c, for a pointer in cycle, it means
  22. // l1 = c - l2, ie. dis(head, entry) = dis(meeting, entry).
  23. if (!head) return null
  24. let slow = head
  25. let fast = head
  26. let entry = head
  27. while (fast.next && fast.next.next) {
  28. slow = slow.next
  29. fast = fast.next.next
  30. if (fast === slow) {
  31. while (entry !== slow) {
  32. entry = entry.next
  33. slow = slow.next
  34. }
  35. return entry
  36. }
  37. }
  38. return null
  39. }
  40. function __main__() {
  41. /* eslint no-console: ["error", {"allow": ["log"]}] */
  42. const logger = console.log.bind(console)
  43. const n5 = new ListNode(5)
  44. const n4 = new ListNode(4)
  45. n4.next = n5
  46. const n3 = new ListNode(3)
  47. n3.next = n4
  48. const n2 = new ListNode(2)
  49. n2.next = n3
  50. const n1 = new ListNode(1)
  51. n1.next = n2
  52. n5.next = n3
  53. logger(n3)
  54. logger(detectCycle(n1))
  55. }
  56. __main__()