codeparrot/xlcost-text-to-code huggingface dataset:
Count bases which contains a set bit as the Most Significant Bit in the representation of N | Function to count bases having MSB of N as a set bit ; Store the required count ; Iterate over the range [ 2 , N ] ; Store the MSB of N ; If MSB is 1 , then increment the count by 1 ; Return the count ; Driver code
function countOfBase ( N ) { let count = 0 ; for ( let i = 2 ; i <= N ; ++ i ) { let highestPower = parseInt ( Math . log ( N ) / Math . log ( i ) ) ; let firstDigit = parseInt ( N / Math . pow ( i , highestPower ) ) ; if ( firstDigit == 1 ) { ++ count ; } } return count ; } let N = 6 ; document . write ( countOfBase ( N ) )
K | Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the string temp ; Print the k digit from last ; Given Input ; Function call
function kthDigitFromLast ( n , k ) { if ( k <= 0 ) { document . write ( - 1 ) ; return ; } var temp = String ( n ) ; if ( k > temp . length ) { document . write ( - 1 ) ; } else { var req = temp . charAt ( temp . length - k ) document . write ( Number ( req ) ) ; } } var n = 2354 ; var k = 2 ; kthDigitFromLast ( n , k ) ;
Count ways to split array into three non | Function to count ways to split array into three subarrays with equal Bitwise XOR ; Stores the XOR value of arr [ ] ; Update the value of arr_xor ; Stores the XOR value of prefix and suffix array respectively ; Stores the ending points of all the required prefix arrays ; Stores the count of suffix arrays whose XOR value is equal to the total XOR value at each index ; Find all prefix arrays with XOR value equal to arr_xor ; Update pref_xor ; Fill the values of suff_inds [ ] ; Update suff_xor ; Update suff_inds [ i ] ; Stores the total number of ways ; Count total number of ways ; Return the final count ; Given Input ; Function Call
function countWays ( arr , N ) { let arr_xor = 0 ; for ( let i = 0 ; i < N ; i ++ ) arr_xor ^= arr [ i ] ; let pref_xor = 0 , suff_xor = 0 ; let pref_ind = [ ] ; let suff_inds = new Array ( N + 1 ) ; suff_inds . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { pref_xor ^= arr [ i ] ; if ( pref_xor == arr_xor ) pref_ind . push ( i ) ; } for ( let i = N - 1 ; i >= 0 ; i -- ) { suff_xor ^= arr [ i ] ; suff_inds [ i ] += suff_inds [ i + 1 ] ; if ( suff_xor == arr_xor ) suff_inds [ i ] ++ ; } let tot_ways = 0 ; for ( let idx of pref_ind ) { if ( idx < N - 1 ) tot_ways += suff_inds [ idx + 2 ] ; } return tot_ways ; } let arr = [ 7 , 0 , 5 , 2 , 7 ] ; let N = arr . length ; document . write ( countWays ( arr , N ) ) ;
Count pairs up to N having sum equal to their XOR | 2D array for memoization ; Recursive Function to count pairs ( x , y ) such that x + y = x ^ y ; If the String is traversed completely ; If the current subproblem is already calculated ; If bound = 1 and s [ i ] = = '0' , only ( 0 , 0 ) can be placed ; Otherwise ; Placing ( 0 , 1 ) and ( 1 , 0 ) are equivalent . Hence , multiply by 2. ; Place ( 0 , 0 ) at the current position . ; Return the answer ;  ; Utility Function to convert N to its binary representation ; Function to count pairs ( x , y ) such that x + y = x ^ y ; Convert the number to equivalent binary representation ; Initialize dp array with - 1. ; Print answer returned by recursive function ; Input ; Function call
let dp = new Array ( 1000 ) ; for ( let i = 0 ; i < 1000 ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } function IsSumEqualsXor ( i , n , bound , s ) { if ( i == n ) return 1 ; if ( dp [ i ] [ bound ] != - 1 ) return dp [ i ] [ bound ] ; let ans = 0 ; if ( bound != 0 && s [ i ] == ' ' ) { ans = IsSumEqualsXor ( i + 1 , n , 1 , s ) ; } else { ans = 2 * IsSumEqualsXor ( i + 1 , n , bound != 0 & ( s [ i ] == ' ' ) ? 1 : 0 , s ) ; ans += IsSumEqualsXor ( i + 1 , n , 0 , s ) ; } dp [ i ] [ bound ] = ans return dp [ i ] [ bound ] ; } function reverse ( input ) { let a = input . split ( ' ' ) ; let l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { let temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a . join ( " " ) ; } function convertToBinary ( n ) { let ans = " " ; while ( n > 0 ) { let rem = String . fromCharCode ( n % 2 + 48 ) ; ans += ( rem ) ; n = parseInt ( n / 2 , 10 ) ; } ans = reverse ( ans ) ; return ans ; } function IsSumEqualsXorUtil ( N ) { let s = convertToBinary ( N ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { for ( let j = 0 ; j < dp [ 0 ] . length ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } document . write ( IsSumEqualsXor ( 0 , s . length , 1 , s . split ( ' ' ) ) + " " ) ; } let N = 10 ; IsSumEqualsXorUtil ( N ) ;
Mean of fourth powers of first N natural numbers | Function to find the average of the fourth power of first N natural numbers ; Stores the sum of the fourth powers of first N natural numbers ; Calculate the sum of fourth power ; Return the average ; Driver Code
function findAverage ( N ) { var S = 0 ; var i ; for ( i = 1 ; i <= N ; i ++ ) { S += i * i * i * i ; } return S / N ; } var N = 3 ; document . write ( findAverage ( N ) ) ;
Decimal equivalent of concatenation of absolute difference of floor and rounded | Function to find the decimal equivalent of the new binary array constructed from absolute decimal of floor and the round - off values ; Traverse the givenarray from the end ; Stores the absolute difference between floor and round - off each array element ; If bit / difference is 1 , then calculate the bit by proper power of 2 and add it to result ; Increment the value of power ; Print the result ; Driver Code
function findDecimal ( arr , N ) { let bit , power = 0 , result = 0 ; for ( let i = N - 1 ; i >= 0 ; i -- ) { bit = Math . abs ( Math . floor ( arr [ i ] ) - Math . round ( arr [ i ] ) ) ; if ( bit != 0 ) result += Math . pow ( 2 , power ) ; power ++ ; } document . write ( result ) ; } let arr = [ 1.2 , 2.6 , 4.2 , 6.9 , 3.1 , 21.6 , 91.2 ] ; let N = arr . length ; findDecimal ( arr , N ) ;
Calculate money placed in boxes after N days based on given conditions | Function to find the total money placed in boxes after N days ; Stores the total money ; Iterate for N days ; Adding the Week number ; Adding previous amount + 1 ; Return the total amount ; Input ; Function call to find total money placed
function totalMoney ( N ) { let ans = 0 ; for ( let i = 0 ; i < N ; i ++ ) { ans += Math . floor ( i / 7 ) ; ans += ( i % 7 + 1 ) ; } return ans ; } let N = 15 ; document . write ( totalMoney ( N ) ) ;
Calculate money placed in boxes after N days based on given conditions | Function to find total money placed in the box ; Number of complete weeks ; Remaining days in the last week ; Input ; Function call to find the total money placed
function totalMoney ( N ) { let CompWeeks = Math . floor ( N / 7 ) ; let RemDays = N % 7 ; let X = 28 * CompWeeks + 7 * Math . floor ( ( CompWeeks * ( CompWeeks - 1 ) / 2 ) ) ; let Y = RemDays * Math . floor ( ( RemDays + 1 ) / 2 ) + CompWeeks * RemDays ; let cost = X + Y ; document . write ( cost , ' ' ) ; } let N = 15 ; totalMoney ( N ) ;
Sum of absolute differences of indices of occurrences of each array element | Set 2 | Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous indices ; Initialize 2 arrays left [ ] and right [ ] of size N ; Traverse the given array ; If arr [ i ] is present in the Map ; Update left [ i ] to 0 and update the value of arr [ i ] in map ; Otherwise , get the value from the map and update left [ i ] ; Clear the map to calculate right [ ] array ; Traverse the array arr [ ] in reverse ; If arr [ i ] is present in theMap ; Update right [ i ] to 0 and update the value of arr [ i ] in the Map ; Otherwise get the value from the map and update right [ i ] ; Iterate in the range [ 0 , N - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; Driver Code
class pair { constructor ( count , prevIndex ) { this . count = count ; this . prevIndex = prevIndex ; } } function findSum ( arr , n ) { let map = new Map ( ) ; let left = new Array ( n ) ; let right = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! map . has ( arr [ i ] ) ) { left [ i ] = 0 ; map . set ( arr [ i ] , new pair ( 1 , i ) ) ; } else { let tmp = map . get ( arr [ i ] ) ; left [ i ] = ( tmp . count ) * ( i - tmp . prevIndex ) + left [ tmp . prevIndex ] ; map . set ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } map . clear ( ) ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( ! map . has ( arr [ i ] ) ) { right [ i ] = 0 ; map . set ( arr [ i ] , new pair ( 1 , i ) ) ; } else { let tmp = map . get ( arr [ i ] ) ; right [ i ] = ( tmp . count ) * ( Math . abs ( i - tmp . prevIndex ) ) + right [ tmp . prevIndex ] ; map . set ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } for ( let i = 0 ; i < n ; i ++ ) document . write ( left [ i ] + right [ i ] + " " ) ; } let arr = [ 1 , 3 , 1 , 1 , 2 ] ; let N = arr . length ; findSum ( arr , N ) ;
Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | Function to check if a digit x is present in the number N or not ; Convert N to string ; Traverse the string num ; Return first occurrence of the digit x ; Function to remove the character at a given index from the number ; Convert N to string ; Store the resultant string ; Traverse the string num ; If the number becomes empty after deletion , then return - 1 ; Return the number ; Function to check if A can be reduced to B by performing the operations any number of times ; Create a queue ; Push A into the queue ; Hashmap to check if the element is present in the Queue or not ; Set A as visited ; Iterate while the queue is not empty ; Store the front value of the queue and pop it from it ; If top is equal to B , then return true ; Traverse the array , D [ ] ; Divide top by D [ i ] if it is possible and push the result in q ; If D [ i ] is present at the top ; Remove the first occurrence of D [ i ] from the top and store the new number ; Push newElement into the queue q ; Return false if A can not be reduced to B ; Driver code Given inputs
function isPresent ( n , x ) { let num = ( n ) . toString ( ) ; for ( let i = 0 ; i < num . length ; i ++ ) { if ( ( num [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) == x ) return i ; } return - 1 ; } function removeDigit ( n , index ) { let num = ( n ) . toString ( ) ; let ans = " " ; for ( let i = 0 ; i < num . length ; i ++ ) { if ( i != index ) ans += num [ i ] ; } if ( ans == " " || ( ans . length == 1 && ans [ 0 ] == ' ' ) ) return - 1 ; let x = parseInt ( ans ) ; return x ; } function reduceNtoX ( a , b , d , n ) { let q = [ ] ; q . push ( a ) ; let visited = new Map ( ) ; visited . set ( a , true ) ; while ( q . length != 0 ) { let top = q . shift ( ) ; if ( top < 0 ) continue ; if ( top == b ) return true ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! visited . has ( top / d [ i ] ) ) visited . set ( top / d [ i ] , false ) ; if ( d [ i ] != 0 && top % d [ i ] == 0 && ! visited . get ( top / d [ i ] ) ) { q . push ( top / d [ i ] ) ; visited . set ( top / d [ i ] , true ) ; } let index = isPresent ( top , d [ i ] ) ; if ( index != - 1 ) { let newElement = removeDigit ( top , index ) ; if ( ! visited . has ( newElement ) ) visited . set ( newElement , false ) ; if ( newElement != - 1 && ( ! visited . get ( newElement ) ) ) { q . push ( newElement ) ; visited . set ( newElement , true ) ; } } } } return false ; } let A = 5643 , B = 81 ; let D = [ 3 , 8 , 1 ] ; let N = D . length ; if ( reduceNtoX ( A , B , D , N ) ) document . write ( " " ) ; else document . write ( " " ) ;
Prime triplets consisting of values up to N having difference between two elements equal to the third | Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Consider all numbers to prime initially ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all tultiples of p as false ; Function to find all prime triplets satisfying the given conditions ; Generate all primes up to N ; Stores the triplets ; Iterate over the range [ 3 , N ] ; Check for the condition ; Store the triplets ; Print all the stored triplets ; Driver code
var prime = new Array ( 100000 ) ; function SieveOfEratosthenes ( n ) { prime . fill ( true ) ; for ( var p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } function findTriplets ( N ) { SieveOfEratosthenes ( N ) ; var V = [ ] ; for ( var i = 3 ; i <= N ; i ++ ) { if ( 2 + i <= N && prime [ i ] == true && prime [ 2 + i ] == true ) { var a1 = [ 2 , i , i + 2 ] ; V . push ( a1 ) ; } } for ( var i = 0 ; i < V . length ; i ++ ) { document . write ( V [ i ] [ 0 ] + " " + V [ i ] [ 1 ] + " " + V [ i ] [ 2 ] + " " ) ; } } N = 8 ; findTriplets ( N ) ;
Smallest number which is not coprime with any element of an array | JavaScript program for the above approach ; Function check if a number is prime or not ; Corner cases ; Check if n is divisible by 2 or 3 ; Check for every 6 th number . The above checking allows to skip middle 5 numbers ; Function to store primes in an array ; Function to calculate GCD of two numbers ; Function to find the smallest number which is not coprime with any element of the array arr [ ] ; Function call to fill the prime numbers ; Stores the answer ; Generate all non - empty subsets of the primes [ ] array ; Stores product of the primes ; Checks if temp is coprime with the array or not ; Check if the product temp is not coprime with the whole array ; If the product is not co - prime with the array ; Print the answer ; Given array ; Stores the size of the array
let MAX = 50 let primes = [ ] ; function isPrime ( n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( let i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } function findPrime ( ) { for ( let i = 2 ; i <= MAX ; i ++ ) { if ( isPrime ( i ) ) primes . push ( i ) ; } } function gcd ( a , b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } function findMinimumNumber ( arr , N ) { findPrime ( ) ; let ans = Number . MAX_SAFE_INTEGER ; let n = primes . length ; for ( let i = 1 ; i < ( 1 << n ) ; i ++ ) { let temp = 1 ; for ( let j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) { temp *= primes [ j ] ; } } let check = true ; for ( let k = 0 ; k < N ; k ++ ) { if ( gcd ( temp , arr [ k ] ) == 1 ) { check = false ; break ; } } if ( check ) ans = Math . min ( ans , temp ) ; } document . write ( ans ) ; } let arr = [ 3 , 4 , 6 , 7 , 8 , 9 , 10 ] ; let N = arr . length ; findMinimumNumber ( arr , N ) ;
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | javascript program for the above approach ; Function to check if a number N can be expressed as sum of its digits raised to the power of the count of digits ; Stores the number of digits ; Stores the resultant number ; Return true if both the numbers are same ; Function to precompute and store for all numbers whether they can be expressed ; Mark all the index which are plus perfect number ; If true , then update the value at this index ; Compute prefix sum of the array ; Function to count array elements that can be expressed as the sum of digits raised to the power of count of digits ; Precompute the results ; Traverse the queries ; Prvar the resultant count ; Driver Code ; function call
var R = 100005 ; var arr = Array ( R ) . fill ( 0 ) ; function canExpress ( N ) { var temp = N ; var n = 0 ; while ( N != 0 ) { N = parseInt ( N / 10 ) ; n ++ ; } N = temp ; var sum = 0 ; while ( N != 0 ) { sum += Math . pow ( N % 10 , n ) ; N = parseInt ( N / 10 ) ; } return ( sum == temp ) ; } function precompute ( ) { for ( var i = 1 ; i < R ; i ++ ) { if ( canExpress ( i ) ) { arr [ i ] = 1 ; } } for ( var i = 1 ; i < R ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; } } function countNumbers ( queries , N ) { precompute ( ) ; for ( var i = 0 ; i < N ; i ++ ) { var L1 = queries [ i ] [ 0 ] ; var R1 = queries [ i ] [ 1 ] ; document . write ( ( arr [ R1 ] - arr [ L1 - 1 ] ) + " " ) ; } } var queries = [ [ 1 , 400 ] , [ 1 , 9 ] ] ; var N = queries . length ; countNumbers ( queries , N ) ;
Queries to calculate sum of the path from root to a given node in given Binary Tree | Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse the queries ; arraylist to store integers
function sumOfNodeInAPath ( node_value ) { let sum_of_node = 0 ; while ( node_value ) { sum_of_node += node_value ; node_value = Math . floor ( node_value / 2 ) ; } document . write ( sum_of_node ) ; return ; } function findSum ( Q ) { for ( let i = 0 ; i < Q . length ; i ++ ) { let node_value = Q [ i ] ; sumOfNodeInAPath ( node_value ) ; document . write ( " " ) ; } } let arr = [ 1 , 5 , 20 , 100 ] ; findSum ( arr ) ;
Minimum removals required to make frequency of all remaining array elements equal | Function to count the minimum removals required to make frequency of all array elements equal ; Stores frequency of all array elements ; Traverse the array ; Stores all the frequencies ; Traverse the map ; Sort the frequencies ; Count of frequencies ; Stores the final count ; Traverse the vector ; Count the number of removals for each frequency and update the minimum removals required ; Print the final count ; Given array ; Size of the array ; Function call to print the minimum number of removals required
function minDeletions ( arr , N ) { var freq = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( freq . has ( arr [ i ] ) ) { freq . set ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . set ( arr [ i ] , 1 ) ; } } var v = [ ] ; freq . forEach ( ( value , key ) => { v . push ( value ) ; } ) ; v . sort ( ) ; var size = v . length ; var ans = N - ( v [ 0 ] * size ) ; for ( var i = 1 ; i < v . length ; i ++ ) { if ( v [ i ] != v [ i - 1 ] ) { var safe = v [ i ] * ( size - i ) ; ans = Math . min ( ans , N - safe ) ; } } document . write ( ans ) ; } var arr = [ 2 , 4 , 3 , 2 , 5 , 3 ] ; var N = arr . length ; minDeletions ( arr , N ) ;
Linked List | Set 2 ( Inserting a node ) | This function is in LinkedList class . Inserts a new Node at front of the list . This method is defined inside LinkedList class shown above ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to povar to new Node
function push ( new_data ) { var new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; }
Linked List | Set 2 ( Inserting a node ) | This function is in LinkedList class . Inserts a new node after the given prev_node . This method is defined inside LinkedList class shown above ; 1. Check if the given Node is null ; 2. Allocate the Node & 3. Put in the data ; 4. Make next of new Node as next of prev_node ; 5. make next of prev_node as new_node
function insertAfter ( prev_node , new_data ) { if ( prev_node == null ) { document . write ( " " ) ; return ; } var new_node = new Node ( new_data ) ; new_node . next = prev_node . next ; prev_node . next = new_node ; }
Find Length of a Linked List ( Iterative and Recursive ) | Linked list Node ; Linked List class head of list ; Inserts a new Node at front of the list . ; * 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to povar to new Node ; Returns count of nodes in linked list ; Base case ; Count is this node plus rest of the list ; Wrapper over getCountRec ( ) ; Start with the empty list
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function push ( new_data ) { var new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } function getCountRec ( node ) { if ( node == null ) return 0 ; return 1 + getCountRec ( node . next ) ; } function getCount ( ) { return getCountRec ( head ) ; } push ( 1 ) ; push ( 3 ) ; push ( 1 ) ; push ( 2 ) ; push ( 1 ) ; document . write ( " " + getCount ( ) ) ;
Write a function that counts the number of times a given int occurs in a Linked List | Counts the no . of occurrences of a node ( search_for ) in a linked list ( head )
function count ( head , key ) { if ( head == null ) return 0 ; if ( head . data == key ) return 1 + count ( head . next , key ) ; return count ( head . next , key ) ; }
Swap nodes in a linked list without swapping data | JavaScript program to swap two given nodes of a linked list ; head of list ; Function to swap Nodes x and y in linked list by changing links ; Nothing to do if x and y are same ; Search for x ( keep track of prevX and CurrX ) ; Search for y ( keep track of prevY and currY ) ; If either x or y is not present , nothing to do ; If x is not head of linked list ; make y the new head ; If y is not head of linked list ; make x the new head ; Swap next pointers ; Function to add Node at beginning of list . ; 1. alloc the Node and put the data ; 2. Make next of new Node as head ; 3. Move the head to point to new Node ; This function prints contents of linked list starting from the given Node ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } var head ; function swapNodes ( x , y ) { if ( x == y ) return ; var prevX = null , currX = head ; while ( currX != null && currX . data != x ) { prevX = currX ; currX = currX . next ; } var prevY = null , currY = head ; while ( currY != null && currY . data != y ) { prevY = currY ; currY = currY . next ; } if ( currX == null currY == null ) return ; if ( prevX != null ) prevX . next = currY ; else head = currY ; if ( prevY != null ) prevY . next = currX ; else head = currX ; var temp = currX . next ; currX . next = currY . next ; currY . next = temp ; } function push ( new_data ) { var new_Node = new Node ( new_data ) ; new_Node . next = head ; head = new_Node ; } function printList ( ) { var tNode = head ; while ( tNode != null ) { document . write ( tNode . data + " " ) ; tNode = tNode . next ; } } push ( 7 ) ; push ( 6 ) ; push ( 5 ) ; push ( 4 ) ; push ( 3 ) ; push ( 2 ) ; push ( 1 ) ; document . write ( " " ) ; printList ( ) ; swapNodes ( 4 , 3 ) ; document . write ( " " ) ; printList ( ) ;
Check if a linked list is Circular Linked List | Link list Node ; * This function returns true if given linked list is circular , else false . ; An empty linked list is circular ; Next of head ; This loop would stop in both cases ( 1 ) If Circular ( 2 ) Not circular ; If loop stopped because of circular condition ; Utility function to create a new node . ; Start with the empty list ; Making linked list circular
class Node { constructor ( val ) { this . data = val ; this . next = null ; } } function isCircular ( head ) { if ( head == null ) return true ; node = head . next ; while ( node != null && node != head ) node = node . next ; return ( node == head ) ; } function newNode ( data ) { temp = new Node ( ) ; temp . data = data ; temp . next = null ; return temp ; } head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; document . write ( isCircular ( head ) ? " " : " " ) ; head . next . next . next . next = head ; document . write ( isCircular ( head ) ? " " : " " ) ;
Circular Singly Linked List | Insertion |  ; This function is only for empty list ; Creating a node dynamically . ; Assigning the data . ; Note : list was empty . We link single node to itself .
function addToEmpty ( last , data ) { if ( last != null ) return last ; var temp = new Node ( ) ; temp . data = data ; last = temp ; temp . next = last ; return last ; }
Circular Singly Linked List | Insertion |  ; Creating a node dynamically . ; Assigning the data . ; Adjusting the links .
function addBegin ( last , data ) { if ( last == null ) return addToEmpty ( last , data ) ; var temp = new Node ( ) ; temp . data = data ; temp . next = last . next ; last . next = temp ; return last ; }