Count triplets in a sorted doubly linked list whose product is equal to a given value x | javascript implementation to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' Represents node of a doubly linked list ; function to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; generate all possible triplets ; if elements in the current triplet sum up to ' x ' ; increment count ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; start with an empty doubly linked list ; insert values in sorted order
class Node { constructor ( val ) { this . data = val ; this . prev = null ; this . next = null ; } } function countTriplets ( head , x ) { var ptr1 , ptr2 , ptr3 ; var count = 0 ; for ( ptr1 = head ; ptr1 != null ; ptr1 = ptr1 . next ) for ( ptr2 = ptr1 . next ; ptr2 != null ; ptr2 = ptr2 . next ) for ( ptr3 = ptr2 . next ; ptr3 != null ; ptr3 = ptr3 . next ) if ( ( ptr1 . data * ptr2 . data * ptr3 . data ) == x ) count ++ ; return count ; } function insert ( head , val ) { temp = new Node ( val ) ; if ( head == null ) head = temp ; else { temp . next = head ; head . prev = temp ; head = temp ; } return head ; } head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; var x = 8 ; document . write ( " " + countTriplets ( head , x ) ) ;