C++ Program to Find the Sum of Last N Nodes of the Given Linked List

You are currently viewing C++ Program to Find the Sum of Last N Nodes of the Given Linked List

C++ Program To 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
#include <bits/stdc++.h>
using namespace std;
 
// A Linked list node
struct Node
{
int data;
struct Node* next;
};
 
// Function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref,
int new_data)
{
// Allocate node
struct Node* new_node = new Node;
 
// Put in the data
new_node->data = new_data;
 
// Link the old list to the new node
new_node->next = (*head_ref);
 
// Move the head to point to the
// new node
(*head_ref) = new_node;
}
 
// Function to recursively find the sum of last
// 'n' nodes of the given linked list
void sumOfLastN_Nodes(struct Node* head,
int* n, int* sum)



{
// if head = NULL
if (!head)
return;
 
// Recursively traverse the remaining nodes
sumOfLastN_Nodes(head->next, n, sum);
 
// if node count 'n' is greater than 0
if (*n > 0)
{
// Accumulate sum
*sum = *sum + head->data;
 
// Reduce node count 'n' by 1
--*n;
}
}
 
// Utility function to find the sum of
// last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head,
int n)
{
// if n == 0
if (n <= 0)
return 0;
 
int sum = 0;
 
// Find the sum of last 'n' nodes
sumOfLastN_Nodes(head, &n, &sum);
 
// Required sum
return sum;
}



 
// Driver code
int main()
{
struct Node* head = NULL;
 
// Create linked list 10->6->8->4->12
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;
}

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply