Find the sum of last n nodes of the given Linked List - GeeksforGeeks

05 Apr, 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++
Java
Python3
C#
Javascript
// 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 listvoid 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 listvoid 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' nodesint 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 program to test aboveint 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;}
// Java implementation to find the sum of// last 'n' nodes of the Linked Listimport 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 liststatic 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 liststatic 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' nodesstatic 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 Codepublic 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
# Python3 implementation to find the sum of# last 'n' nodes of the Linked List # Linked List nodeclass Node:    def __init__(self, data):        self.data = data        self.next = None head = Nonen = 0sum = 0 # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data):    global head         # allocate node    new_node = Node(0)         # 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 listdef sumOfLastN_Nodes(head):     global sum    global n     # if head = None    if (head == None):        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 = n - 1     # utility function to find the sum of last 'n' nodesdef sumOfLastN_NodesUtil(head, n):         global sum         # 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 Codehead = None # create linked list 10.6.8.4.12push(head, 12)push(head, 4)push(head, 8)push(head, 6)push(head, 10) n = 2print("Sum of last " , n ,    " nodes = ", sumOfLastN_NodesUtil(head, n)) # This code is contributed by Arnab Kundu
// C# implementation to find the sum of// last 'n' nodes of the Linked Listusing System;     class GFG{     /* A Linked list node */public class Node{    public int data;    public Node next;};static Node head;static int n, sum; // function to insert a node at the// beginning of the linked liststatic 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 liststatic 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' nodesstatic 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 Codepublic 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;    Console.Write("Sum of last " + n +                  " nodes = " +                  sumOfLastN_NodesUtil(head, n));}} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation to find the sum of// last 'n' nodes of the Linked List         /* A Linked list node */    class Node    {        constructor()        {            this.data;            this.next;        }    }         let head;    let n, sum;    // function to insert a node at the    // beginning of the linked list    function push(head_ref,new_data)    {        /* allocate node */    let 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    function sumOfLastN_Nodes(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    function sumOfLastN_NodesUtil(head,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    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;    document.write("Sum of last " + n +                     " nodes = " +                     sumOfLastN_NodesUtil(head, n));      // This code is contributed by unknown2108</script>
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++
Java
Python3
C#
Javascript
// 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 listvoid 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;} // utility function to find the sum of last 'n' nodesint sumOfLastN_NodesUtil(struct Node* head, int n){    // if n == 0    if (n <= 0)        return 0;     stack<int> st;    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--) {        sum += st.top();        st.pop();    }     // required sum    return sum;} // Driver program to test aboveint 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;}
// Java implementation to find the sum of last// 'n' nodes of the Linked Listimport 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 liststatic 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' nodesstatic 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 program to test abovepublic 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
# Python3 implementation to find the sum of# last 'n' nodes of the Linked List # Linked List nodeclass Node:    def __init__(self, data):        self.data = data        self.next = None head = Nonen = 0sum = 0 # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data):    global head         # allocate node    new_node = Node(0)         # 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' nodesdef sumOfLastN_NodesUtil(head, n):         global sum         # if n == 0    if (n <= 0):        return 0         st = []    sum = 0         # traverses the list from left to right    while (head != None):                 # push the node's data onto the stack 'st'        st.append(head.data)                 # move to next node        head = head.next         # pop 'n' nodes from 'st' and    # add them    while (n):        n -= 1        sum += st[0]        st.pop(0)             # required sum    return sum # Driver Codehead = None # create linked list 10.6.8.4.12push(head, 12)push(head, 4)push(head, 8)push(head, 6)push(head, 10) n = 2print("Sum of last" , n ,    "nodes =", sumOfLastN_NodesUtil(head, n)) # This code is contributed by shubhamsingh10
// C# implementation to find the sum of last// 'n' nodes of the Linked Listusing System;using System.Collections.Generic; class GFG{ /* A Linked list node */class Node{    public int data;    public Node next;}; // function to insert a node at the// beginning of the linked liststatic 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' nodesstatic int sumOfLastN_NodesUtil(Node head, int n){    // if n == 0    if (n <= 0)        return 0;     Stack<int> st = new Stack<int>();    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 codepublic 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;    Console.Write("Sum of last " + n+ " nodes = "        + sumOfLastN_NodesUtil(head, n));}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation to find the sum of last// 'n' nodes of the Linked List         /* A Linked list node */    class Node    {        constructor()        {            let data,next;        }    }         // function to insert a node at the// beginning of the linked list    function push(head_ref,new_data)    {        /* allocate node */        let 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    function sumOfLastN_NodesUtil(head,n)    {        // if n == 0    if (n <= 0)        return 0;      let st = [];    let 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[st.length-1];        st.pop();    }      // required sum    return sum;    }         // Driver program to test above    let 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);      let n = 2;    document.write("Sum of last " + n+ " nodes = "        + sumOfLastN_NodesUtil(head, n));                 // This code is contributed by patel2127</script>
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.
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++
Java
Python3
C#
Javascript
// 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 listvoid 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;} 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;} // utility function to find the sum of last 'n' nodesint sumOfLastN_NodesUtil(struct Node* head, int n){    // if n == 0    if (n <= 0)        return 0;     // reverse the linked list    reverseList(&head);     int sum = 0;    struct Node* current = head;     // traverse the 1st 'n' nodes of the reversed    // linked list and add them    while (current != NULL && n--) {                           // 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 program to test aboveint 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;}
// Java implementation to find the sum of last// 'n' nodes of the Linked Listimport 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 liststatic 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' nodesstatic 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 codepublic 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 */
# Python implementation to find the sum of last# 'n' Nodes of the Linked List''' A Linked list Node ''' # A Linked list Nodeclass Node:     def __init__(self, x):        self.data = x        self.next = None head = None # Function to insert a Node at the# beginning of the linked listdef push(head_ref, new_data):       # Allocate Node    new_Node = Node(new_data)     # 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    return head def reverseList():    global head;    current, prev, next = None, None, None;    current = head;    prev = None;     while (current != None):        next = current.next;        current.next = prev;        prev = current;        current = next;     head = prev; # utility function to find the sum of last 'n' Nodesdef sumOfLastN_NodesUtil(n):       # if n == 0    if (n <= 0):        return 0;     # reverse the linked list    reverseList();     sum = 0;    current = head;     # traverse the 1st 'n' Nodes of the reversed    # linked list and add them    while (current != None and n > 0):               # accumulate Node's data to 'sum'        sum += current.data;         # move to next Node        current = current.next;        n -= 1;     # reverse back the linked list    reverseList();     # required sum    return sum; # Driver codeif __name__ == '__main__':    # create linked list 10.6.8.4.12     # 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)     n = 2;    print("Sum of last " , n , " Nodes = " , sumOfLastN_NodesUtil(n)); # This code contributed by Princi Singh
// C# implementation to find the sum of last// 'n' nodes of the Linked Listusing System; class GFG{     /* A Linked list node */public class Node{    public int data;    public Node next;};static Node head; // function to insert a node at the// beginning of the linked liststatic 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' nodesstatic 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 codepublic 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;    Console.WriteLine("Sum of last " + n + " nodes = "        + sumOfLastN_NodesUtil(n));}} // This code is contributed by Rajput-Ji
<script>// javascript implementation to find the sum of last// 'n' nodes of the Linked List /* A Linked list node */     class Node {            constructor() {                this.data = 0;                this.next = null;            }        }var head; // function to insert a node at the// beginning of the linked listfunction push(head_ref , new_data){    /* allocate node */    var 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 reverseList(head_ref){    var 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' nodesfunction sumOfLastN_NodesUtil(n){    // if n == 0    if (n <= 0)        return 0;     // reverse the linked list    reverseList(head);     var sum = 0;    var 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       // create linked list 10.6.8.4.12    push(head, 12);    push(head, 4);    push(head, 8);    push(head, 6);    push(head, 10);     var n = 2;    document.write("Sum of last " + n + " nodes = "        + sumOfLastN_NodesUtil(n)); // This code contributed by umadevi9616</script>
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.
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++
Java
Python3
C#
Javascript
// 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 listvoid 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;} // utility function to find the sum of last 'n' nodesint sumOfLastN_NodesUtil(struct Node* head, int n){    // if n == 0    if (n <= 0)        return 0;     int sum = 0, len = 0;    struct 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--)                           // 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 program to test aboveint 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;}
// 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 liststatic 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' nodesstatic 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 codepublic 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
# Python3 implementation to find the sum# of last 'n' Nodes of the Linked List # A Linked list Nodeclass Node:         def __init__(self, x):                 self.data = x        self.next = None         head = None # Function to insert a Node at the# beginning of the linked listdef push(head_ref, new_data):         # Allocate Node    new_Node = Node(new_data)     # 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    return head # Utility function to find the sum of# last 'n' Nodesdef sumOfLastN_NodesUtil(head, n):         # If n == 0    if (n <= 0):        return 0     sum = 0    len = 0    temp = head         # Calculate the length of the linked list    while (temp != None):        len += 1        temp = temp.next     # Count of first (len - n) Nodes    c = len - n    temp = head     # Just traverse the 1st 'c' Nodes    while (temp != None and c > 0):                 # Move to next Node        temp = temp.next        c -= 1     # Now traverse the last 'n' Nodes    # and add them    while (temp != None):                 # Accumulate Node's data to sum        sum += temp.data         # Move to next Node        temp = temp.next     # Required sum    return sum # Driver codeif __name__ == '__main__':         # 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)     n = 2         print("Sum of last ", n, " Nodes = ",          sumOfLastN_NodesUtil(head, n)) # This code is contributed by Princi Singh
// C# implementation to find the sum of last// 'n' nodes of the Linked Listusing System;     class GFG{  /* A Linked list node */public class Node{    public int data;    public Node next;};static Node head; // function to insert a node at the// beginning of the linked liststatic 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' nodesstatic 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 codepublic 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;    Console.WriteLine("Sum of last " + n + " nodes = "        + sumOfLastN_NodesUtil(head, n));}} // This code is contributed by Princi Singh
<script> // Javascript implementation to// find the sum of last// 'n' nodes of the Linked List    /* A Linked list node */class Node {    constructor() {        this.data = 0;        this.next = null;    }}     var head;     // function to insert a node at the    // beginning of the linked list    function push( head_ref , new_data)    {        /* allocate 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    function sumOfLastN_NodesUtil( head , n)    {        // if n == 0        if (n <= 0)            return 0;         var sum = 0, len = 0;         temp = head;         // calculate the length of the linked list        while (temp != null) {            len++;            temp = temp.next;        }         // count of first (len - n) nodes        var 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              // create linked list 10.6.8.4.12        push(head, 12);        push(head, 4);        push(head, 8);        push(head, 6);        push(head, 10);         var n = 2;        document.write("Sum of last " + n        + " nodes = " + sumOfLastN_NodesUtil(head, n)); // This code contributed by umadevi9616 </script>
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++
Java
Python3
C#
Javascript
// 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 listvoid 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;} // utility function to find the sum of last 'n' nodesint sumOfLastN_NodesUtil(struct Node* head, int n){    // if n == 0    if (n <= 0)        return 0;     int sum = 0, temp = 0;    struct 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--) {                          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 program to test aboveint 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;}
// Java implementation to find the sum of last// 'n' nodes of the Linked Listclass 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
# Python3 implementation to find the sum of last# 'n' nodes of the Linked List# include class Node:    def __init__(self, x):        self.data = x        self.next = None # function to insert a node at the# beginning of the linked listdef push(head_ref,new_data):       # /* allocate node */    new_node = Node(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' nodesdef sumOfLastN_NodesUtil(head, n):       # if n == 0    if (n <= 0):        return 0     sum = 0    temp = 0    ref_ptr  = None    main_ptr = None    ref_ptr = main_ptr = head     # traverse 1st 'n' nodes through 'ref_ptr' and    # accumulate all node's data to 'sum'    while (ref_ptr != None and  n):        sum += ref_ptr.data         # move to next node        ref_ptr = ref_ptr.next        n -= 1     # traverse to the end of the linked list    while (ref_ptr != None):         # 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 program to test aboveif __name__ == '__main__':    head = None     # 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)     n = 2    print("Sum of last ",n," nodes = ",sumOfLastN_NodesUtil(head, n)) # This code is contributed by mohit kumar 29
// C# implementation to find the sum of last// 'n' nodes of the Linked Listusing System; class GfG{     // Defining structure    public class Node    {        public int data;        public Node next;    }     static Node head;     static void printList(Node start)    {        Node temp = start;        while (temp != null)        {            Console.Write(temp.data + " ");            temp = temp.next;        }        Console.WriteLine();    }     // 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;         Console.WriteLine("Sum of last " + n +                    " nodes = " + sumOfLastN_NodesUtil(head, n));    }} // This code contributed by Rajput-Ji
<script>// Javascript implementation to find the sum of last// 'n' nodes of the Linked List         // Defining structure    class Node    {        constructor()        {            let node,next;        }    }         let head;         function printList(start)    {        let temp = start;        while (temp != null)        {            document.write(temp.data + " ");            temp = temp.next;        }        document.write("<br>");    }         // Push function    function push(start,info)    {        // Allocating node        let 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;    }         function sumOfLastN_NodesUtil(head,n)    {        // if n == 0        if (n <= 0)            return 0;          let sum = 0, temp = 0;        let 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    head = null;          // Adding elements to Linked List        push(head, 12);        push(head, 4);        push(head, 8);        push(head, 6);        push(head, 10);                    let n = 2;          document.write("Sum of last " + n +                    " nodes = " + sumOfLastN_NodesUtil(head, n));           // This code is contributed by avanitrachhadiya2155</script>
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)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nobody_cares
Rajput-Ji
rahulverma153
29AjayKumar
princi singh
princiraj1992
andrew1234
SHUBHAMSINGH10
mohit kumar 29
umadevi9616
unknown2108
patel2127
avanitrachhadiya2155
simranarora5sos
surinderdawra388
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List vs Array
Delete a Linked List node at a given position
Implement a stack using singly linked list
Queue - Linked List Implementation
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)
Remove duplicates from a sorted linked list
Function to check if a singly linked list is palindrome
Find Length of a Linked List (Iterative and Recursive)
Top 20 Linked List Interview Question