Guest User

Untitled

a guest
Nov 15th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. /*
  2. Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node.
  3. Note that the intersection is defined based on reference not value. That is, if the kth node of the first
  4. linked list is the exact same node (by reference) as the jth node of the second linked list, then they are
  5. intersecting.
  6. */
  7. function getIntersection(h1: Node, h2: Node) {
  8. const nodes1 = getNodesMap(h1)
  9. const nodes2 = getNodesMap(h2)
  10.  
  11. let intersection = null
  12. nodes1.forEach(n => {
  13. if (nodes2.get(n)) {
  14. intersection = n
  15. }
  16. return n
  17. })
  18.  
  19. return intersection
  20. }
  21.  
  22.  
  23. function getNodesMap(head: Node): Map<Node, Node> {
  24. const nodes = new Map()
  25. nodes.set(head, head)
  26.  
  27. let node = head
  28. while (node.next) {
  29. node = node.next
  30. if (!nodes.get(node)) {
  31. nodes.set(node, node)
  32. } else {
  33. break // loop found
  34. }
  35. }
  36.  
  37. return nodes
  38. }
Add Comment
Please, Sign In to add comment