Find the sum of last n nodes of the given Linked List
Last Updated :
13 Jul, 2022
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.
Constraints: 0 <= n <= number of nodes in the linked list.
Examples:
Input : 10->6->8->4->12, n = 2
Output : 16
Sum of last two nodes:
12 + 4 = 16
Input : 15->7->9->5->16->14, n = 4
Output : 44
Method 1: (Recursive approach using system call stack):
Recursively traverse the linked list up to the end. Now during the return from the function calls, add up the last n nodes. The sum can be accumulated in some variable passed by reference to the function or to some global variable.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void sumOfLastN_Nodes( struct Node* head, int * n,
int * sum)
{
if (!head)
return ;
sumOfLastN_Nodes(head->next, n, sum);
if (*n > 0) {
*sum = *sum + head->data;
--*n;
}
}
int sumOfLastN_NodesUtil( struct Node* head, int n)
{
if (n <= 0)
return 0;
int sum = 0;
sumOfLastN_Nodes(head, &n, &sum);
return sum;
}
int main()
{
struct Node* head = NULL;
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node next;
};
static Node head;
static int n, sum;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
static void sumOfLastN_Nodes(Node head)
{
if (head == null )
return ;
sumOfLastN_Nodes(head.next);
if (n > 0 )
{
sum = sum + head.data;
--n;
}
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0 )
return 0 ;
sum = 0 ;
sumOfLastN_Nodes(head);
return sum;
}
public static void main(String[] args)
{
head = null ;
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));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
head = None
n = 0
sum = 0
def push(head_ref, new_data):
global head
new_node = Node( 0 )
new_node.data = new_data
new_node. next = head_ref
head_ref = new_node
head = head_ref
def sumOfLastN_Nodes(head):
global sum
global n
if (head = = None ):
return
sumOfLastN_Nodes(head. next )
if (n > 0 ) :
sum = sum + head.data
n = n - 1
def sumOfLastN_NodesUtil(head, n):
global sum
if (n < = 0 ):
return 0
sum = 0
sumOfLastN_Nodes(head)
return sum
head = None
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))
|
C#
using System;
class GFG
{
public class Node
{
public int data;
public Node next;
};
static Node head;
static int n, sum;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
static void sumOfLastN_Nodes(Node head)
{
if (head == null )
return ;
sumOfLastN_Nodes(head.next);
if (n > 0)
{
sum = sum + head.data;
--n;
}
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0)
return 0;
sum = 0;
sumOfLastN_Nodes(head);
return sum;
}
public static void Main(String[] args)
{
head = null ;
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));
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data;
this .next;
}
}
let head;
let n, sum;
function push(head_ref,new_data)
{
let new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
function sumOfLastN_Nodes(head)
{
if (head == null )
return ;
sumOfLastN_Nodes(head.next);
if (n > 0)
{
sum = sum + head.data;
--n;
}
}
function sumOfLastN_NodesUtil(head,n)
{
if (n <= 0)
return 0;
sum = 0;
sumOfLastN_Nodes(head);
return sum;
}
head = null ;
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));
</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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int sumOfLastN_NodesUtil( struct Node* head, int n)
{
if (n <= 0)
return 0;
stack< int > st;
int sum = 0;
while (head != NULL) {
st.push(head->data);
head = head->next;
}
while (n--) {
sum += st.top();
st.pop();
}
return sum;
}
int main()
{
struct Node* head = NULL;
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0 )
return 0 ;
Stack<Integer> st = new Stack<Integer>();
int sum = 0 ;
while (head != null )
{
st.push(head.data);
head = head.next;
}
while (n-- > 0 )
{
sum += st.peek();
st.pop();
}
return sum;
}
public static void main(String[] args)
{
Node head = null ;
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));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
head = None
n = 0
sum = 0
def push(head_ref, new_data):
global head
new_node = Node( 0 )
new_node.data = new_data
new_node. next = head_ref
head_ref = new_node
head = head_ref
def sumOfLastN_NodesUtil(head, n):
global sum
if (n < = 0 ):
return 0
st = []
sum = 0
while (head ! = None ):
st.append(head.data)
head = head. next
while (n):
n - = 1
sum + = st[ 0 ]
st.pop( 0 )
return sum
head = None
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))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0)
return 0;
Stack< int > st = new Stack< int >();
int sum = 0;
while (head != null )
{
st.Push(head.data);
head = head.next;
}
while (n-- >0)
{
sum += st.Peek();
st.Pop();
}
return sum;
}
public static void Main(String[] args)
{
Node head = null ;
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));
}
}
|
Javascript
<script>
class Node
{
constructor()
{
let data,next;
}
}
function push(head_ref,new_data)
{
let new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
function sumOfLastN_NodesUtil(head,n)
{
if (n <= 0)
return 0;
let st = [];
let sum = 0;
while (head != null )
{
st.push(head.data);
head = head.next;
}
while (n-- >0)
{
sum += st[st.length-1];
st.pop();
}
return sum;
}
let head = null ;
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));
</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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void reverseList( struct Node** head_ref)
{
struct Node* current, *prev, *next;
current = *head_ref;
prev = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
int sumOfLastN_NodesUtil( struct Node* head, int n)
{
if (n <= 0)
return 0;
reverseList(&head);
int sum = 0;
struct Node* current = head;
while (current != NULL && n--) {
sum += current->data;
current = current->next;
}
reverseList(&head);
return sum;
}
int main()
{
struct Node* head = NULL;
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node next;
};
static Node head;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
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;
}
static int sumOfLastN_NodesUtil( int n)
{
if (n <= 0 )
return 0 ;
reverseList(head);
int sum = 0 ;
Node current = head;
while (current != null && n-- > 0 )
{
sum += current.data;
current = current.next;
}
reverseList(head);
return sum;
}
public static void main(String[] args)
{
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));
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
head = None
def push(head_ref, new_data):
new_Node = Node(new_data)
new_Node.data = new_data
new_Node. next = head_ref
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;
def sumOfLastN_NodesUtil(n):
if (n < = 0 ):
return 0 ;
reverseList();
sum = 0 ;
current = head;
while (current ! = None and n > 0 ):
sum + = current.data;
current = current. next ;
n - = 1 ;
reverseList();
return sum ;
if __name__ = = '__main__' :
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));
|
C#
using System;
class GFG
{
public class Node
{
public int data;
public Node next;
};
static Node head;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
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;
}
static int sumOfLastN_NodesUtil( int n)
{
if (n <= 0)
return 0;
reverseList(head);
int sum = 0;
Node current = head;
while (current != null && n-- >0)
{
sum += current.data;
current = current.next;
}
reverseList(head);
return sum;
}
public static void Main(String[] args)
{
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));
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
var head;
function push(head_ref , new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
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;
}
function sumOfLastN_NodesUtil(n)
{
if (n <= 0)
return 0;
reverseList(head);
var sum = 0;
var current = head;
while (current != null && n-- >0)
{
sum += current.data;
current = current.next;
}
reverseList(head);
return sum;
}
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));
</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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int sumOfLastN_NodesUtil( struct Node* head, int n)
{
if (n <= 0)
return 0;
int sum = 0, len = 0;
struct Node* temp = head;
while (temp != NULL) {
len++;
temp = temp->next;
}
int c = len - n;
temp = head;
while (temp != NULL && c--)
temp = temp->next;
while (temp != NULL) {
sum += temp->data;
temp = temp->next;
}
return sum;
}
int main()
{
struct Node* head = NULL;
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
|
Java
class GFG
{
static class Node
{
int data;
Node next;
};
static Node head;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0 )
return 0 ;
int sum = 0 , len = 0 ;
Node temp = head;
while (temp != null )
{
len++;
temp = temp.next;
}
int c = len - n;
temp = head;
while (temp != null &&c-- > 0 )
{
temp = temp.next;
}
while (temp != null )
{
sum += temp.data;
temp = temp.next;
}
return sum;
}
public static void main(String[] args)
{
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));
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
head = None
def push(head_ref, new_data):
new_Node = Node(new_data)
new_Node.data = new_data
new_Node. next = head_ref
head_ref = new_Node
head = head_ref
return head
def sumOfLastN_NodesUtil(head, n):
if (n < = 0 ):
return 0
sum = 0
len = 0
temp = head
while (temp ! = None ):
len + = 1
temp = temp. next
c = len - n
temp = head
while (temp ! = None and c > 0 ):
temp = temp. next
c - = 1
while (temp ! = None ):
sum + = temp.data
temp = temp. next
return sum
if __name__ = = '__main__' :
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))
|
C#
using System;
class GFG
{
public class Node
{
public int data;
public Node next;
};
static Node head;
static void push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0)
return 0;
int sum = 0, len = 0;
Node temp = head;
while (temp != null )
{
len++;
temp = temp.next;
}
int c = len - n;
temp = head;
while (temp != null &&c-- >0)
{
temp = temp.next;
}
while (temp != null )
{
sum += temp.data;
temp = temp.next;
}
return sum;
}
public static void Main(String[] args)
{
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));
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
var head;
function push( head_ref , new_data)
{
new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
head = head_ref;
}
function sumOfLastN_NodesUtil( head , n)
{
if (n <= 0)
return 0;
var sum = 0, len = 0;
temp = head;
while (temp != null ) {
len++;
temp = temp.next;
}
var c = len - n;
temp = head;
while (temp != null && c-- > 0) {
temp = temp.next;
}
while (temp != null ) {
sum += temp.data;
temp = temp.next;
}
return sum;
}
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));
</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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int sumOfLastN_NodesUtil( struct Node* head, int n)
{
if (n <= 0)
return 0;
int sum = 0, temp = 0;
struct Node* ref_ptr, *main_ptr;
ref_ptr = main_ptr = head;
while (ref_ptr != NULL && n--) {
sum += ref_ptr->data;
ref_ptr = ref_ptr->next;
}
while (ref_ptr != NULL) {
temp += main_ptr->data;
sum += ref_ptr->data;
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
return (sum - temp);
}
int main()
{
struct Node* head = NULL;
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
|
Java
class GfG
{
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();
}
static void push(Node start, int info)
{
Node node = new Node();
node.data = info;
node.next = start;
head = node;
}
private static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0 )
return 0 ;
int sum = 0 , temp = 0 ;
Node ref_ptr, main_ptr;
ref_ptr = main_ptr = head;
while (ref_ptr != null && (n--) > 0 )
{
sum += ref_ptr.data;
ref_ptr = ref_ptr.next;
}
while (ref_ptr != null )
{
temp += main_ptr.data;
sum += ref_ptr.data;
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
return (sum - temp);
}
public static void main(String[] args)
{
head = null ;
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));
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
def push(head_ref,new_data):
new_node = Node(new_data)
new_node. next = head_ref
head_ref = new_node
return head_ref
def sumOfLastN_NodesUtil(head, n):
if (n < = 0 ):
return 0
sum = 0
temp = 0
ref_ptr = None
main_ptr = None
ref_ptr = main_ptr = head
while (ref_ptr ! = None and n):
sum + = ref_ptr.data
ref_ptr = ref_ptr. next
n - = 1
while (ref_ptr ! = None ):
temp + = main_ptr.data
sum + = ref_ptr.data
main_ptr = main_ptr. next
ref_ptr = ref_ptr. next
return ( sum - temp)
if __name__ = = '__main__' :
head = None
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))
|
C#
using System;
class GfG
{
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();
}
static void push(Node start, int info)
{
Node node = new Node();
node.data = info;
node.next = start;
head = node;
}
private static int sumOfLastN_NodesUtil(Node head, int n)
{
if (n <= 0)
return 0;
int sum = 0, temp = 0;
Node ref_ptr, main_ptr;
ref_ptr = main_ptr = head;
while (ref_ptr != null && (n--) > 0)
{
sum += ref_ptr.data;
ref_ptr = ref_ptr.next;
}
while (ref_ptr != null )
{
temp += main_ptr.data;
sum += ref_ptr.data;
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
return (sum - temp);
}
public static void Main(String[] args)
{
head = null ;
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));
}
}
|
Javascript
<script>
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>" );
}
function push(start,info)
{
let node = new Node();
node.data = info;
node.next = start;
head = node;
}
function sumOfLastN_NodesUtil(head,n)
{
if (n <= 0)
return 0;
let sum = 0, temp = 0;
let ref_ptr, main_ptr;
ref_ptr = main_ptr = head;
while (ref_ptr != null && (n--) > 0)
{
sum += ref_ptr.data;
ref_ptr = ref_ptr.next;
}
while (ref_ptr != null )
{
temp += main_ptr.data;
sum += ref_ptr.data;
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
return (sum - temp);
}
head = null ;
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));
</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)
Share your thoughts in the comments
Please Login to comment...