Finding next greater node for each node in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in the head of the linked list as the first and the only argument.

This linkedlist contains numerical data. Each node in the list may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0.

Our function should prepare and return an array in which the corresponding element is the next greater element for the element in the list.

For example, if the list is −

Then the output should be −

const output = [7, 0, 5, 5, 0];

Output Explanation:

Because the next greater element of 2 is 7, for 7 there is no greater element and so on.

Example

The code for this will be −

 Live Demo

class Node{
   constructor(data){
      this.data = data;
      this.next = null;
   };
};
class LinkedList{
   constructor(){
      this.head = null;
      this.size = 0;
   };
};
LinkedList.prototype.add = function(data){
   const newNode = new Node(data);
   let curr
   if(this.head === null){
      this.head = newNode;
   }else{
      curr = this.head;
      while (curr.next) {
         curr = curr.next;
      }
      curr.next = newNode;
   };
   this.size++;
};
const list = new LinkedList();
list.add(2);
list.add(7);
list.add(4);
list.add(3);
list.add(5);
const nextGreater = (head) => {
   const arr = [];
   const res = [];
   let curr = head;
   let currentIndex = 0
   while(curr){
      while (arr.length > 0 && curr.data > arr[arr.length - 1][1]) {
         const [index] = arr.pop();
         res[index] = curr.data;
      };
      arr.push([currentIndex, curr.data]);
      currentIndex += 1;
      curr = curr.next;
   };
   for(let i = 0; i < currentIndex; i++){
      if(res[i] === undefined){
         res[i] = 0;
      };
   };
   return res;
};
console.log(nextGreater(list.head));

Output

And the output in the console will be −

[ 7, 0, 5, 5, 0 ]
raja
Published on 07-Apr-2021 08:07:03
Advertisements