समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो लिंक्ड लिस्ट के हेड को पहले और एकमात्र आर्गुमेंट के रूप में लेता है।
इस लिंक्डलिस्ट में संख्यात्मक डेटा होता है। सूची में प्रत्येक नोड का एक अगला बड़ा मान हो सकता है: node_i के लिए, next_larger(node_i) वह node_j.val है जैसे कि j > i, node_j.val > node_i.val, और j सबसे छोटा संभव विकल्प है। यदि ऐसा j मौजूद नहीं है, तो अगला बड़ा मान 0 है।
हमारे फ़ंक्शन को एक सरणी तैयार करके वापस करनी चाहिए जिसमें संबंधित तत्व सूची में तत्व के लिए अगला बड़ा तत्व हो।
उदाहरण के लिए, यदि सूची है -

तो आउटपुट होना चाहिए -
const output = [7, 0, 5, 5, 0];
आउटपुट व्याख्या:
क्योंकि 2 का अगला बड़ा तत्व 7 है, 7 के लिए कोई बड़ा तत्व नहीं है और इसी तरह।
उदाहरण
इसके लिए कोड होगा -
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));
आउटपुट
कंसोल में आउटपुट होगा -
[ 7, 0, 5, 5, 0 ]