ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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 ]