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

• Last Updated : 06 Sep, 2022

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:

Javascript



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:

Javascript



Output

48

Time complexity: O(n)

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 multiply them.
4. Reverse the linked list back to its original order.
5. Return the product.

Below is the implementation of the above approach:

Javascript



Output

48

Time complexity: O(n)

Method 4 (Using a 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 product them.
4. Return the product.

Below is the implementation of the above approach:

Javascript



Output

48

Time complexity: O(n)

My Personal Notes arrow_drop_up