Find the sum of last n nodes of the given Linked List | Java implementation to find the sum of last ' n ' nodes of the 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 ; calculate the length of the linked list ; count of first ( len - n ) nodes ; just traverse the 1 st ' c ' nodes ; move to next node ; now traverse the last ' n ' nodes and add them ; accumulate node 's data to sum ; move to next node ; required sum ; Driver code ; create linked list 10.6 .8 .4 .12
class GFG { static class Node { int data ; Node next ; } ; static Node head ; static void push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; head = head_ref ; } static int sumOfLastN_NodesUtil ( Node head , int n ) { if ( n <= 0 ) return 0 ; int sum = 0 , len = 0 ; Node temp = head ; while ( temp != null ) { len ++ ; temp = temp . next ; } int c = len - n ; temp = head ; while ( temp != null && c -- > 0 ) { temp = temp . next ; } while ( temp != null ) { sum += temp . data ; temp = temp . next ; } return sum ; } public static void main ( String [ ] args ) { push ( head , 12 ) ; push ( head , 4 ) ; push ( head , 8 ) ; push ( head , 6 ) ; push ( head , 10 ) ; int n = 2 ; System . out . println ( " Sum ▁ of ▁ last ▁ " + n + " ▁ nodes ▁ = ▁ " + sumOfLastN_NodesUtil ( head , n ) ) ; } }