C++ Program To Find The Sum Of Last N Nodes Of The Given Linked List
Last Updated :
04 Jul, 2022
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.
Constraints: 0 <= n <= number of nodes in the linked list.
Examples:
Input: 10->6->8->4->12, n = 2
Output: 16
Sum of last two nodes:
12 + 4 = 16
Input: 15->7->9->5->16->14, n = 4
Output: 44
Method 1: (Recursive approach using system call stack)
Recursively traverse the linked list up to the end. Now during the return from the function calls, add up the last n nodes. The sum can be accumulated in some variable passed by reference to the function or to some global variable.
C++
#include <bits/stdc++.h>
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 sumOfLastN_Nodes( struct Node* head,
int * n, int * sum)
{
if (!head)
return ;
sumOfLastN_Nodes(head->next, n, sum);
if (*n > 0)
{
*sum = *sum + head->data;
--*n;
}
}
int sumOfLastN_NodesUtil( struct Node* head,
int n)
{
if (n <= 0)
return 0;
int sum = 0;
sumOfLastN_Nodes(head, &n, &sum);
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;
}
|
Output:
Sum of last 2 nodes = 16
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), if system call stack is being considered.
Method 2: (Iterative approach using user-defined stack)
It is an iterative procedure to the recursive approach explained in Method 1 of this post. Traverses the nodes from left to right. While traversing pushes the nodes to a user-defined stack. Then pops the top n values from the stack and adds them.
C++
#include <bits/stdc++.h>
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;
}
int sumOfLastN_NodesUtil( struct Node* head,
int n)
{
if (n <= 0)
return 0;
stack< int > st;
int sum = 0;
while (head != NULL)
{
st.push(head->data);
head = head->next;
}
while (n--)
{
sum += st.top();
st.pop();
}
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;
}
|
Output:
Sum of last 2 nodes = 16
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), stack size
Method 3 (Reversing the linked list):
Following are the steps:
- Reverse the given linked list.
- Traverse the first n nodes of the reversed linked list.
- While traversing add them.
- Reverse the linked list back to its original order.
- Return the added sum.
C++
#include <bits/stdc++.h>
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;
}
|
Output:
Sum of last 2 nodes = 16
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Method 4 (Using the length of linked list):
Following are the steps:
- Calculate the length of the given Linked List. Let it be len.
- First, traverse the (len – n) nodes from the beginning.
- Then traverse the remaining n nodes and while traversing add them.
- Return the added sum.
C++
#include <bits/stdc++.h>
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;
}
int sumOfLastN_NodesUtil( struct Node* head,
int n)
{
if (n <= 0)
return 0;
int sum = 0, len = 0;
struct Node* temp = head;
while (temp != NULL)
{
len++;
temp = temp->next;
}
int c = len - n;
temp = head;
while (temp != NULL && c--)
temp = temp->next;
while (temp != NULL)
{
sum += temp->data;
temp = temp->next;
}
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;
}
|
Output:
Sum of last 2 nodes = 16
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Method 5 (Use of two pointers requires single traversal):
Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move reference pointer to n nodes from head and while traversing accumulate node’s data to some variable, say sum. Now move both pointers simultaneously until the reference pointer reaches the end of the list and while traversing accumulate all node’s data to sum pointed by the reference pointer and accumulate all node’s data to some variable, say, temp, pointed by the main pointer. Now, (sum – temp) is the required sum of the last n nodes.
C++
#include <bits/stdc++.h>
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;
}
int sumOfLastN_NodesUtil( struct Node* head,
int n)
{
if (n <= 0)
return 0;
int sum = 0, temp = 0;
struct Node* ref_ptr, *main_ptr;
ref_ptr = main_ptr = head;
while (ref_ptr != NULL && n--)
{
sum += ref_ptr->data;
ref_ptr = ref_ptr->next;
}
while (ref_ptr != NULL)
{
temp += main_ptr->data;
sum += ref_ptr->data;
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
return (sum - temp);
}
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;
}
|
Output:
Sum of last 2 nodes = 16
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Please refer complete article on Find the sum of last n nodes of the given Linked List for more details!
Similar Reads
C++ Program For Inserting Node In The Middle Of The Linked List
Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
5 min read
C++ Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1->2->3->4->NULL Output : Even Input : 1->2->3->4->5->NULL Output : OddRecommended: Please solve it on "PRACTICE" first, before moving o
3 min read
C++ Program For Finding The Length Of Loop In Linked List
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Re
3 min read
C++ Program to Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d As
4 min read
C++ Program For Removing Every K-th Node Of The Linked List
Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples : Input: 1->2->3->4->5->6->7->8 k = 3 Output: 1->2->4->5->7->8 As 3 is the k-th node after its deletion list would be 1->2->4->5->6->7->
3 min read
C++ Program To Delete N Nodes After M Nodes Of A Linked List
Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples: Input: M = 2, N = 2 Linked List: 1->2->3->4->5->6->7->8 Output: Linked L
3 min read
C++ Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one t
3 min read
C++ Program To Delete Middle Of Linked List
Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
4 min read
C++ Program For Finding The Middle Element Of A Given Linked List
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
6 min read
C++ Program For Segregating Even And Odd Nodes In A Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers the same. Examples: Input: 17->15->8->12->10->5->4->1->7->6-
7 min read