Count triplets in a sorted doubly linked list whose product is equal to a given value x | Java 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 ; Driver code ; start with an empty doubly linked list ; insert values in sorted order
import java . util . * ; class Node { public int data ; public Node prev , next ; public Node ( int val ) { data = val ; prev = null ; next = null ; } } class GFG { static int countTriplets ( Node head , int x ) { Node ptr1 , ptr2 , ptr3 ; int 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 ; } static Node insert ( Node head , int val ) { Node temp = new Node ( val ) ; if ( head == null ) head = temp ; else { temp . next = head ; head . prev = temp ; head = temp ; } return head ; } public static void main ( String [ ] args ) { Node 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 ) ; int x = 8 ; System . out . println ( " count ▁ = ▁ " + countTriplets ( head , x ) ) ; } }