Find the product of last N nodes of the given Linked List

Given a linked list and a number N. Find the product of last n nodes of the linked list.

Constraints : 0 <= N <= number of nodes in the linked list.

Examples:

Input : List = 10->6->8->4->12, N = 2
Output : 48
Explanation : Product of last two nodes:
              12 * 4 = 48

Input : List = 15->7->9->5->16->14, N = 4
Output : 10080
Explanation : Product of last four nodes:
              9 * 5 * 16 * 14 = 10080

Method 1:(Iterative approach using user defined stack) Traverse the nodes from left to right. While traversing push the nodes to a user defined stack. Then pops the top n values from the stack and find their product.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the product 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 list
void 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 product of last 'n' nodes
int productOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;
  
    stack<int> st;
    int prod = 1;
  
    // 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--) {
        prod *= st.top();
        st.pop();
    }
  
    // required product
    return prod;
}
  
// Driver program to test above
int 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 << productOfLastN_NodesUtil(head, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the product 
// of last 'n' nodes of the Linked List
import java.util.*;
class GFG 
{
  
/* A Linked list node */
static class Node 
{
    int data;
    Node next;
};
static Node head;
  
// function to insert a node at the
// beginning of the linked list
static void push(Node head_ref, 
                 int new_data)
{
    /* allocate node */
    Node new_node = new Node();
  
    /* put in the data */
    new_node.data = new_data;
  
    /* link the old list to the new node */
    new_node.next = (head_ref);
  
    /* move the head to point to the new node */
    (head_ref) = new_node;
    head = head_ref;
}
  
// utility function to find the product 
// of last 'n' nodes
static int productOfLastN_NodesUtil(Node head,
                                        int n)
{
    // if n == 0
    if (n <= 0)
        return 0;
  
    Stack<Integer> st = new Stack<Integer>();
    int prod = 1;
  
    // 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
    {
        prod *= st.peek();
        st.pop();
    }
  
    // required product
    return prod;
}
  
// Driver Code
public static void main(String[] args) 
{
    head = null;
  
    // create linked list 10->6->8->4->12
    push(head, 12);
    push(head, 4);
    push(head, 8);
    push(head, 6);
    push(head, 10);
  
    int n = 2;
    System.out.println(productOfLastN_NodesUtil(head, n));
}
}
  
// This code is contributed by PrinciRaj1992 

chevron_right


C#

// C# implementation to find the product
// of last ‘n’ nodes of the Linked List
using System;
using System.Collections.Generic;

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 list
static void push(Node head_ref,
int new_data)
{
/* allocate node */
Node new_node = new Node();

/* put in the data */
new_node.data = new_data;

/* link the old list to the new node */
new_node.next = (head_ref);

/* move the head to point to the new node */
(head_ref) = new_node;
head = head_ref;
}

// utility function to find the product
// of last ‘n’ nodes
static int productOfLastN_NodesUtil(Node head,
int n)
{
// if n == 0
if (n <= 0) return 0; Stack st = new Stack();
int prod = 1;

// 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)
{
prod *= st.Peek();
st.Pop();
}

// required product
return prod;
}

// Driver Code
public static void Main(String[] args)
{
head = null;

// create linked list 10->6->8->4->12
push(head, 12);
push(head, 4);
push(head, 8);
push(head, 6);
push(head, 10);

int n = 2;
Console.WriteLine(productOfLastN_NodesUtil(head, n));
}
}

// This code is contributed by 29AjayKumar

Output:

48

Time complexity : O(n)

Method 2: (Recursive approach using system call stack) Recursively traverse the linked list up to the end. Now during the return from the function calls, multiply the last n nodes. The product can be accumulated in some variable passed by reference to the function or to some global variable.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the product 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 list
void 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 product of last
// 'n' nodes of the given linked list
void productOfLastN_Nodes(struct Node* head, int* n,
                          int* prod)
{
    // if head = NULL
    if (!head)
        return;
  
    // recursively traverse the remaining nodes
    productOfLastN_Nodes(head->next, n, prod);
  
    // if node count 'n' is greater than 0
    if (*n > 0) {
  
        // accumulate sum
        *prod = *prod * head->data;
  
        // reduce node count 'n' by 1
        --*n;
    }
}
  
// utility function to find the product of last 'n' nodes
int productOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;
  
    int prod = 1;
  
    // find the sum of last 'n' nodes
    productOfLastN_Nodes(head, &n, &prod);
  
    // required product
    return prod;
}
  
// Driver program to test above
int 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 << productOfLastN_NodesUtil(head, n);
    return 0;
}

chevron_right


Output:

48

Time complexity : O(n)
Method 3 (Reversing the linked list):

  1. Following are the steps:
  2. Reverse the given linked list.
  3. Traverse the first n nodes of the reversed linked list.
  4. While traversing multiply them.
  5. Reverse the linked list back to its original order.
  6. Return the product.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the product 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 list
void 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 product of last 'n' nodes
int productOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;
  
    // reverse the linked list
    reverseList(&head);
  
    int prod = 1;
    struct Node* current = head;
  
    // traverse the 1st 'n' nodes of the reversed
    // linked list and product them
    while (current != NULL && n--) {
  
        // accumulate node's data to 'sum'
        prod *= current->data;
  
        // move to next node
        current = current->next;
    }
  
    // reverse back the linked list
    reverseList(&head);
  
    // required product
    return prod;
}
  
// Driver program to test above
int 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 << productOfLastN_NodesUtil(head, n);
    return 0;
}

chevron_right


Output:

48

Time complexity : O(n)
Method 4 (Using length of linked list):

  1. Following are the steps:
  2. Calculate the length of the given Linked List. Let it be len.
  3. First traverse the (len – n) nodes from the beginning.
  4. Then traverse the remaining n nodes and while traversing product them.
  5. Return the product.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the product 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 list
void 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 product of last 'n' nodes
int productOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;
  
    int prod = 1, 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
        prod *= temp->data;
  
        // move to next node
        temp = temp->next;
    }
  
    // required product
    return prod;
}
  
// Driver program to test above
int 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 << productOfLastN_NodesUtil(head, n);
    return 0;
}

chevron_right


Output:

48

Time complexity : O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.