Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program To Delete N Nodes After M Nodes Of A Linked List
Next article icon

Python Program To Find The Sum Of Last N Nodes Of The Given Linked List

Last Updated : 18 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

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.

Python3




# Python3 implementation to find the sum of
# last 'n' nodes of the Linked List
  
# Linked List node 
class Node: 
    def __init__(self, data): 
        self.data = data 
        self.next = None
  
head = None
n = 0
sum = 0
  
# Function to insert a node at the
# beginning of the linked list
def 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 list
def 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' nodes
def 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 Code
head = None
  
# 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
print("Sum of last " , n , 
      " nodes = ", 
      sumOfLastN_NodesUtil(head, n))
  
# This code is contributed by Arnab Kundu
 
 

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.

Python3




# Python3 implementation to find the sum of 
# last 'n' nodes of the Linked List 
  
# Linked List node 
class Node: 
    def __init__(self, data): 
        self.data = data 
        self.next = None
  
head = None
n = 0
sum = 0
  
# Function to insert a node at the 
# beginning of the linked list 
def 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' nodes 
def 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 Code 
head = None
  
# 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
print("Sum of last" , n , 
      "nodes =", 
      sumOfLastN_NodesUtil(head, n)) 
# This code is contributed by shubhamsingh10 
 
 

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:  

  1. Reverse the given linked list.
  2. Traverse the first n nodes of the reversed linked list.
  3. While traversing add them.
  4. Reverse the linked list back to its original order.
  5. Return the added sum.

Python3




# Python implementation to find the sum of last
# 'n' Nodes of the Linked List
''' A Linked list Node '''
  
# A Linked list Node
class Node:
  
    def __init__(self, x):
        self.data = x
        self.next = None
  
head = None
  
# Function to insert a Node at the
# beginning of the linked list
def 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 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' Nodes
def 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 code
if __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(n));
# This code is contributed by Princi Singh
 
 

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: 

  1. Calculate the length of the given Linked List. Let it be len.
  2. First, traverse the (len – n) nodes from the beginning.
  3. Then traverse the remaining n nodes and while traversing add them.
  4. Return the added sum.

Python3




# Python3 implementation to find the sum 
# of last 'n' Nodes of the Linked List
  
# A Linked list Node 
class Node:
      
    def __init__(self, x):        
        self.data = x
        self.next = None
          
head = None
  
# Function to insert a Node at the
# beginning of the linked list
def 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' Nodes
def 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 code
if __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 
 
 

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.

Python3




# Python3 implementation to find the sum 
# of last 'n' nodes of the Linked List
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
  
# Function to insert a node at the
# beginning of the linked list
def 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' nodes
def 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 code
if __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
 
 

 
 

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!
 



Next Article
Python Program To Delete N Nodes After M Nodes Of A Linked List
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Python Programs
  • Python-DSA
Practice Tags :
  • Linked List

Similar Reads

  • Python 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->
    4 min read
  • Python 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
    4 min read
  • Python 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
  • Python 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
    4 min read
  • Python 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
  • Python3 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 = 2Output : c d e a b Input : a b c d e f g h N = 4Output : e f g h a b c
    4 min read
  • Python Program To Delete Alternate Nodes Of A Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    3 min read
  • Python Program For Finding Intersection Of Two Sorted Linked Lists
    Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.  Example:  Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Ou
    4 min read
  • Python 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
    4 min read
  • Python 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences