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 povar to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; reverse the linked list ; traverse the 1 st ' n ' nodes of the reversed linked list and add them ; accumulate node ' s ▁ data ▁ to ▁ ' sum ' ; move to next node ; reverse back the linked list ; required sum ; create linked list 10.6 .8 .4 .12
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } var head ; function push ( head_ref , new_data ) { var new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; head = head_ref ; } function reverseList ( head_ref ) { var current , prev , next ; current = head_ref ; prev = null ; while ( current != null ) { next = current . next ; current . next = prev ; prev = current ; current = next ; } head_ref = prev ; head = head_ref ; } function sumOfLastN_NodesUtil ( n ) { if ( n <= 0 ) return 0 ; reverseList ( head ) ; var sum = 0 ; var current = head ; while ( current != null && n -- > 0 ) { sum += current . data ; current = current . next ; } reverseList ( head ) ; return sum ; } push ( head , 12 ) ; push ( head , 4 ) ; push ( head , 8 ) ; push ( head , 6 ) ; push ( head , 10 ) ; var n = 2 ; document . write ( " " + n + " " + sumOfLastN_NodesUtil ( n ) ) ;