Sum of Last n Nodes in a Linked List

Last Updated : 17 May, 2026

Given a single linked list, calculate the sum of the last nodes.

Examples:  

Input: Linked List: 5->9->6->3->4->10, n = 3

2056957920

Output: 17
Explanation: The sum of the last 3 nodes in the linked list is 3 + 4 + 10 = 17.

Input: Linked List: 1->2, n = 2

2056957921

Output: 3
Explanation: The sum of the 2 two nodes in the linked list is 2 + 1 = 3.

Try It Yourself
redirect icon

[Naive Approach] Two Traversals - O(n) Time O(1) Space

The idea is to first find the total number of nodes in the linked list. Once the length is known, we skip the first (len - n) nodes and then traverse the remaining last n nodes, accumulating their sum.

C++
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// your task is to complete this function
// function should return sum of last n nodes
int sumofNodes(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 != nullptr)
    {
        len++;
        temp = temp->next;
    }

    // count of first (len - n) nodes
    int c = len - n;
    temp = head;

    // just traverse the 1st 'c' nodes
    while (temp != nullptr && c--)
        temp = temp->next;

    // now traverse the last 'n' nodes and add them
    while (temp != nullptr)
    {

        // accumulate node's data to sum
        sum += temp->data;

        // move to next node
        temp = temp->next;
    }

    // required sum
    return sum;
}

//Driver Code
int main() {

    // create linked list 5->9->6->3->4->10
    Node* head = new Node(5);
    head->next = new Node(9);
    head->next->next = new Node(6);
    head->next->next->next = new Node(3);
    head->next->next->next->next = new Node(4);
    head->next->next->next->next->next = new Node(10);

    int n = 3;

    cout << sumofNodes(head, n);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

struct Node* newNode(int x)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = x;
    node->next = NULL;
    return node;
}

// your task is to complete this function
// function should return sum of last n nodes
int sumofNodes(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--)
        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
int main()
{

    // create linked list 5->9->6->3->4->10
    struct Node* head = newNode(5);
    head->next = newNode(9);
    head->next->next = newNode(6);
    head->next->next->next = newNode(3);
    head->next->next->next->next = newNode(4);
    head->next->next->next->next->next = newNode(10);

    int n = 3;

    printf("%d", sumofNodes(head, n));

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int x)
    {
        data = x;
        next = null;
    }
}

class GfG {
    
    // your task is to complete this function
    // function should return sum of last n nodes
    public static int sumofNodes(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)
            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;
    }

    public static void main(String[] args)
    {

        // create linked list 5->9->6->3->4->10
        Node head = new Node(5);
        head.next = new Node(9);
        head.next.next = new Node(6);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(4);
        head.next.next.next.next.next = new Node(10);

        int n = 3;

        System.out.print(sumofNodes(head, n));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


# your task is to complete this function
# function should return sum of last n nodes
def sumofNodes(head, n):

    # if n == 0
    if n <= 0:
        return 0

    sum = 0
    length = 0
    temp = head

    # calculate the length of the linked list
    while temp is not None:
        length += 1
        temp = temp.next

    # count of first (len - n) nodes
    c = length - n
    temp = head

    # just traverse the 1st 'c' nodes
    while temp is not None and c > 0:
        temp = temp.next
        c -= 1

    # now traverse the last 'n' nodes and add them
    while temp is not None:

        # accumulate node's data to sum
        sum += temp.data

        # move to next node
        temp = temp.next

    # required sum
    return sum

if __name__ == "__main__":

    # create linked list 5->9->6->3->4->10
    head = Node(5)
    head.next = Node(9)
    head.next.next = Node(6)
    head.next.next.next = Node(3)
    head.next.next.next.next = Node(4)
    head.next.next.next.next.next = Node(10)

    n = 3

    print(sumofNodes(head, n))
C#
using System;

public class Node
{
  public int data;
  public Node next;

  public Node(int x)
  {
      data = x;
      next = null;
  }
}

public class GfG
{
  // your task is to complete this function
  // function should return sum of last n nodes
  public int sumofNodes(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)
          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() 
  {
      // create linked list 5->9->6->3->4->10
      Node head = new Node(5);
      head.next = new Node(9);
      head.next.next = new Node(6);
      head.next.next.next = new Node(3);
      head.next.next.next.next = new Node(4);
      head.next.next.next.next.next = new Node(10);

      int n = 3;
      GfG obj = new GfG();

      Console.WriteLine(obj.sumofNodes(head, n));
  }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.next = null;
    }
}

// your task is to complete this function
// function should return sum of last n nodes
function sumofNodes(head, n)
{

    // if n == 0
    if (n <= 0)
        return 0;

    let sum = 0, len = 0;
    let temp = head;

    // calculate the length of the linked list
    while (temp !== null) {
        len++;
        temp = temp.next;
    }

    // count of first (len - n) nodes
    let c = len - n;
    temp = head;

    // just traverse the 1st 'c' nodes
    while (temp !== null && c--)
        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 5->9->6->3->4->10
let head = new Node(5);
head.next = new Node(9);
head.next.next = new Node(6);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(4);
head.next.next.next.next.next = new Node(10);

let n = 3;

console.log(sumofNodes(head, n));

Output
17

Time Complexity: O(n), where n is the number of nodes in the linked list. 
Auxiliary Space: O(1)

[Expected Approach] Single Traversal - O(n) Time O(1) Space

The idea is to use a two-pointer (sliding window) technique to find the sum of the last n nodes in a single traversal. We maintain a window of size n. First, we compute the sum of the first n nodes. Then, we slide the window forward by adding the next node and removing the previous node’s contribution.

Let us understand with an example:

Linked List: 5 -> 9 -> 6 -> 3 -> 4 -> 10, n = 3

Start traversal: Initialize sum = 0, temp = 0
First 3 nodes:

  • At 5 -> sum = 5
  • At 9 -> sum = 14
  • At 6 -> sum = 20

Now slide window:

  • At 3 -> sum = 23, temp = 5
  • At 4 -> sum = 27, temp = 14
  • At 10 -> sum = 37, temp = 20

All nodes processed. Final value = sum - temp = 17

C++
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int x)
    {
        data = x;
        next = nullptr;
    }
};

// Function to calculate the sum of the last n nodes in a linked list
int sumofNodes(Node *head, int n)
{
    // If n is less than or equal to 0, return 0
    if (n <= 0)
        return 0;

    int sum = 0, temp = 0;
    Node *ref_ptr, *main_ptr;
    ref_ptr = main_ptr = head;

    // Calculate the sum of the first n nodes
    while (ref_ptr != nullptr && n--)
    {
        sum += ref_ptr->data;
        ref_ptr = ref_ptr->next;
    }

    // Calculate the sum of the remaining nodes
    while (ref_ptr != nullptr)
    {
        temp += main_ptr->data;
        sum += ref_ptr->data;
        main_ptr = main_ptr->next;
        ref_ptr = ref_ptr->next;
    }

    // Return the sum of the last n nodes
    return (sum - temp);
}

// Driver Code
int main()
{
    Node *head = new Node(5);
    head->next = new Node(9);
    head->next->next = new Node(6);
    head->next->next->next = new Node(3);
    head->next->next->next->next = new Node(4);
    head->next->next->next->next->next = new Node(10);

    int n = 3;

    cout << sumofNodes(head, n);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

// Function to create a new node
struct Node* newNode(int x)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = x;
    node->next = NULL;
    return node;
}

// Function to calculate the sum of the last n nodes in a linked list
int sumofNodes(struct Node *head, int n)
{
    // If n is less than or equal to 0, return 0
    if (n <= 0)
        return 0;

    int sum = 0, temp = 0;
    struct Node *ref_ptr, *main_ptr;
    ref_ptr = main_ptr = head;

    // Calculate the sum of the first n nodes
    while (ref_ptr != NULL && n--)
    {
        sum += ref_ptr->data;
        ref_ptr = ref_ptr->next;
    }

    // Calculate the sum of the remaining nodes
    while (ref_ptr != NULL)
    {
        temp += main_ptr->data;
        sum += ref_ptr->data;
        main_ptr = main_ptr->next;
        ref_ptr = ref_ptr->next;
    }

    // Return the sum of the last n nodes
    return (sum - temp);
}

// Driver Code
int main()
{
    struct Node *head = newNode(5);
    head->next = newNode(9);
    head->next->next = newNode(6);
    head->next->next->next = newNode(3);
    head->next->next->next->next = newNode(4);
    head->next->next->next->next->next = newNode(10);

    int n = 3;

    printf("%d", sumofNodes(head, n));

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node next;

    Node(int x)
    {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to calculate the sum of the last n nodes in
    // a linked list
    public static int sumofNodes(Node head, int n)
    {
        // If n is less than or equal to 0, return 0
        if (n <= 0)
            return 0;

        int sum = 0, temp = 0;
        Node ref_ptr, main_ptr;
        ref_ptr = main_ptr = head;

        // Calculate the sum of the first n nodes
        while (ref_ptr != null && n-- > 0) {
            sum += ref_ptr.data;
            ref_ptr = ref_ptr.next;
        }

        // Calculate the sum of the remaining nodes
        while (ref_ptr != null) {
            temp += main_ptr.data;
            sum += ref_ptr.data;
            main_ptr = main_ptr.next;
            ref_ptr = ref_ptr.next;
        }

        // Return the sum of the last n nodes
        return (sum - temp);
    }

    public static void main(String[] args)
    {
        Node head = new Node(5);
        head.next = new Node(9);
        head.next.next = new Node(6);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(4);
        head.next.next.next.next.next = new Node(10);

        int n = 3;

        System.out.print(sumofNodes(head, n));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


# Function to calculate the sum of the last n nodes in a linked list
def sumofNodes(head, n):

    # If n is less than or equal to 0, return 0
    if n <= 0:
        return 0

    sum = 0
    temp = 0
    ref_ptr = head
    main_ptr = head

    # Calculate the sum of the first n nodes
    while ref_ptr is not None and n:
        sum += ref_ptr.data
        ref_ptr = ref_ptr.next
        n -= 1

    # Calculate the sum of the remaining nodes
    while ref_ptr is not None:
        temp += main_ptr.data
        sum += ref_ptr.data
        main_ptr = main_ptr.next
        ref_ptr = ref_ptr.next

    # Return the sum of the last n nodes
    return (sum - temp)


# Driver Code
if __name__ == "__main__":
    head = Node(5)
    head.next = Node(9)
    head.next.next = Node(6)
    head.next.next.next = Node(3)
    head.next.next.next.next = Node(4)
    head.next.next.next.next.next = Node(10)

    n = 3

    print(sumofNodes(head, n))
C#
using System;

class Node
{
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

class GfG
{
    // Function to calculate the sum of the last n nodes in a linked list
    public int sumofNodes(Node head, int n)
    {
        // If n is less than or equal to 0, return 0
        if (n <= 0)
            return 0;

        int sum = 0, temp = 0;
        Node ref_ptr, main_ptr;
        ref_ptr = main_ptr = head;

        // Calculate the sum of the first n nodes
        while (ref_ptr != null && n-- > 0)
        {
            sum += ref_ptr.data;
            ref_ptr = ref_ptr.next;
        }

        // Calculate the sum of the remaining nodes
        while (ref_ptr != null)
        {
            temp += main_ptr.data;
            sum += ref_ptr.data;
            main_ptr = main_ptr.next;
            ref_ptr = ref_ptr.next;
        }

        // Return the sum of the last n nodes
        return (sum - temp);
    }

    public static void Main()
    {
        Node head = new Node(5);
        head.next = new Node(9);
        head.next.next = new Node(6);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(4);
        head.next.next.next.next.next = new Node(10);

        int n = 3;
        GfG obj = new GfG();
        Console.Write(obj.sumofNodes(head, n));
    }
}
JavaScript
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

// Function to calculate the sum of the last n nodes in a linked list
function sumofNodes(head, n) {
  // If n is less than or equal to 0, return 0
  if (n <= 0)
    return 0;

  let sum = 0, temp = 0;
  let ref_ptr = head, main_ptr = head;

  // Calculate the sum of the first n nodes
  while (ref_ptr!= null && n-- > 0) {
    sum += ref_ptr.data;
    ref_ptr = ref_ptr.next;
  }

  // Calculate the sum of the remaining nodes
  while (ref_ptr!= null) {
    temp += main_ptr.data;
    sum += ref_ptr.data;
    main_ptr = main_ptr.next;
    ref_ptr = ref_ptr.next;
  }

  // Return the sum of the last n nodes
  return (sum - temp);
}

// Driver Code
let head = new Node(5);
head.next = new Node(9);
head.next.next = new Node(6);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(4);
head.next.next.next.next.next = new Node(10);

let n = 3;

console.log(sumofNodes(head, n));

Output
17

Time Complexity: O(n), where n is the number of nodes in the linked list. 
Auxiliary Space: O(1)

Comment