Find the sum of last n nodes of the given Linked List | A Linked list node ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; traverses the list from left to right ; push the node ' s ▁ data ▁ onto ▁ the ▁ stack ▁ ' st ' ; move to next node ; pop ' n ' nodes from ' st ' and add them ; required sum ; Driver program to test above ; create linked list 10.6 .8 .4 .12
class Node { constructor ( ) { let data , next ; } } function push ( head_ref , new_data ) { let new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } function sumOfLastN_NodesUtil ( head , n ) { if ( n <= 0 ) return 0 ; let st = [ ] ; let sum = 0 ; while ( head != null ) { st . push ( head . data ) ; head = head . next ; } while ( n -- > 0 ) { sum += st [ st . length - 1 ] ; st . pop ( ) ; } return sum ; } let head = null ; head = push ( head , 12 ) ; head = push ( head , 4 ) ; head = push ( head , 8 ) ; head = push ( head , 6 ) ; head = push ( head , 10 ) ; let n = 2 ; document . write ( " " + n + " " + sumOfLastN_NodesUtil ( head , n ) ) ;