Java Program To Find The Sum Of Last N Nodes Of The Given Linked List
Last Updated :
23 Jul, 2025
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.
Java
// Java implementation to find the sum of
// last 'n' nodes of the Linked List
import java.util.*;
class GFG{
// A Linked list node
static class Node
{
int data;
Node next;
};
static Node head;
static int n, sum;
// Function to insert a node at the
// beginning of the linked list
static void push(Node head_ref,
int new_data)
{
// Allocate node
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;
head = head_ref;
}
// Function to recursively find the sum of last
// 'n' nodes of the given linked list
static void sumOfLastN_Nodes(Node head)
{
// if head = NULL
if (head == null)
return;
// Recursively traverse the remaining
// nodes
sumOfLastN_Nodes(head.next);
// 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
static int sumOfLastN_NodesUtil(Node head,
int n)
{
// if n == 0
if (n <= 0)
return 0;
sum = 0;
// Find the sum of last 'n' nodes
sumOfLastN_Nodes(head);
// Required sum
return sum;
}
// Driver Code
public static void main(String[] args)
{
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);
n = 2;
System.out.print("Sum of last " + n +
" nodes = " +
sumOfLastN_NodesUtil(head, n));
}
}
// This code is contributed by 29AjayKumar
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.
Java
// Java implementation to find the sum of last
// 'n' nodes of the Linked List
import java.util.*;
class GFG{
// A Linked list node
static class Node
{
int data;
Node next;
};
// Function to insert a node at the
// beginning of the linked list
static Node push(Node head_ref,
int new_data)
{
// Allocate node
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;
return head_ref;
}
// Utility function to find the sum of
// last 'n' nodes
static int sumOfLastN_NodesUtil(Node head,
int n)
{
// if n == 0
if (n <= 0)
return 0;
Stack<Integer> st = new Stack<Integer>();
int sum = 0;
// Traverses the list from left to right
while (head != null)
{
// Push the node's data onto the
// stack 'st'
st.push(head.data);
// Move to next node
head = head.next;
}
// Pop 'n' nodes from 'st' and
// add them
while (n-- >0)
{
sum += st.peek();
st.pop();
}
// Required sum
return sum;
}
// Driver code
public static void main(String[] args)
{
Node head = null;
// Create linked list 10.6.8.4.12
head = push(head, 12);
head = push(head, 4);
head = push(head, 8);
head = push(head, 6);
head = push(head, 10);
int n = 2;
System.out.print("Sum of last " + n +
" nodes = " +
sumOfLastN_NodesUtil(head, n));
}
}
// This code is contributed by 29AjayKumar
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.
Java
// Java implementation to find the sum of last
// 'n' nodes of the Linked List
import java.util.*;
class GFG{
// A Linked list node
static class Node
{
int data;
Node next;
};
static Node head;
// Function to insert a node at the
// beginning of the linked list
static void push(Node head_ref,
int new_data)
{
// Allocate node
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;
head=head_ref;
}
static void reverseList(Node head_ref)
{
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;
head = head_ref;
}
// Utility function to find the sum of
// last 'n' nodes
static int sumOfLastN_NodesUtil(int n)
{
// if n == 0
if (n <= 0)
return 0;
// Reverse the linked list
reverseList(head);
int sum = 0;
Node current = head;
// Traverse the 1st 'n' nodes of the
// reversed linked list and add them
while (current != null && n-- >0)
{
// Accumulate node's data to 'sum'
sum += current.data;
// Move to next node
current = current.next;
}
// Reverse back the linked list
reverseList(head);
// Required sum
return sum;
}
// Driver code
public static void main(String[] args)
{
// 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;
System.out.println("Sum of last " + n +
" nodes = " +
sumOfLastN_NodesUtil(n));
}
}
// This code is contributed by PrinciRaj1992
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.
Java
// Java implementation to find the sum of last
// 'n' nodes of the Linked List
class GFG{
// A Linked list node
static class Node
{
int data;
Node next;
};
static Node head;
// Function to insert a node at the
// beginning of the linked list
static void push(Node head_ref,
int new_data)
{
// Allocate node
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;
head = head_ref;
}
// Utility function to find the sum of
// last 'n' nodes
static int sumOfLastN_NodesUtil(Node head,
int n)
{
// if n == 0
if (n <= 0)
return 0;
int sum = 0, len = 0;
Node temp = head;
// Calculate the length of the
// linked list
while (temp != null)
{
len++;
temp = temp.next;
}
// Count of first (len - n) nodes
int c = len - n;
temp = head;
// Just traverse the 1st 'c' nodes
while (temp != null&&c-- >0)
{
// Move to next node
temp = temp.next;
}
// Now traverse the last 'n' nodes and
// add them
while (temp != null)
{
// Accumulate node's data to sum
sum += temp.data;
// Move to next node
temp = temp.next;
}
// Required sum
return sum;
}
// Driver code
public static void main(String[] args)
{
// 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;
System.out.println("Sum of last " + n +
" nodes = " +
sumOfLastN_NodesUtil(head, n));
}
}
// This code is contributed by 29AjayKumar
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.
Java
// Java implementation to find the sum of last
// 'n' nodes of the Linked List
class GfG
{
// Defining structure
static class Node
{
int data;
Node next;
}
static Node head;
static void printList(Node start)
{
Node temp = start;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Push function
static void push(Node start, int info)
{
// Allocating node
Node node = new Node();
// Info into node
node.data = info;
// Next of new node to head
node.next = start;
// head points to new node
head = node;
}
private static int sumOfLastN_NodesUtil(Node head,
int n)
{
// if n == 0
if (n <= 0)
return 0;
int sum = 0, temp = 0;
Node ref_ptr, main_ptr;
ref_ptr = main_ptr = head;
// Traverse 1st 'n' nodes through 'ref_ptr'
// and accumulate all node's data to 'sum'
while (ref_ptr != null && (n--) > 0)
{
sum += ref_ptr.data;
// Move to next node
ref_ptr = ref_ptr.next;
}
// Traverse to the end of the linked list
while (ref_ptr != null)
{
// Accumulate all node's data to 'temp'
// pointed by the 'main_ptr'
temp += main_ptr.data;
// Accumulate all node's data to 'sum'
// pointed by the 'ref_ptr'
sum += ref_ptr.data;
// Move both the pointers to their
// respective next nodes
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
// Required sum
return (sum - temp);
}
// Driver code
public static void main(String[] args)
{
head = null;
// Adding elements to Linked List
push(head, 12);
push(head, 4);
push(head, 8);
push(head, 6);
push(head, 10);
printList(head);
int n = 2;
System.out.println("Sum of last " + n +
" nodes = " +
sumOfLastN_NodesUtil(head, n));
}
}
// This code is contributed by shubham96301
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
Basics & Prerequisites
Data Structures
Array IntroductionArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
13 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem