Find the sum of last n nodes of the given Linked List | C ++ 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 ; 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 ; Driver program to test above ; create linked list 10 -> 6 -> 8 -> 4 -> 12
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void reverseList ( struct Node * * head_ref ) { struct Node * current , * prev , * next ; current = * head_ref ; prev = NULL ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } * head_ref = prev ; } int sumOfLastN_NodesUtil ( struct Node * head , int n ) { if ( n <= 0 ) return 0 ; reverseList ( & head ) ; int sum = 0 ; struct Node * current = head ; while ( current != NULL && n -- ) { sum += current -> data ; current = current -> next ; } reverseList ( & head ) ; return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 6 ) ; push ( & head , 10 ) ; int n = 2 ; cout << " Sum ▁ of ▁ last ▁ " << n << " ▁ nodes ▁ = ▁ " << sumOfLastN_NodesUtil ( head , n ) ; return 0 ; }