Clean ES6 solution


  • 0
    Y
    function getLength(head) {
      let length = 0
      let pointer = head
      while (pointer) {
        length += 1
        pointer = pointer.next
      }
      return length
    }
    
    function getIntersectionNode(p, q) {
      let x = p
      let y = q
      let xLength = getLength(x)
      let yLength = getLength(y)
      if (yLength > xLength) {
        // without loss of generality x is the longer list
        [x, y] = [y, x];
        [xLength, yLength] = [yLength, xLength]
      }
      let xPointer = x
      let yPointer = y
      let steps = 0
      while (xPointer && steps < xLength - yLength) {
        xPointer = xPointer.next
        steps += 1
      }
      while (xPointer && yPointer && xPointer !== yPointer) {
        xPointer = xPointer.next
        yPointer = yPointer.next
      }
      return xPointer
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.