문제
연결 리스트의 헤드를 첫 번째이자 유일한 인수로 취하는 JavaScript 함수를 작성해야 합니다.
이 연결 목록에는 숫자 데이터가 포함되어 있습니다. 목록의 각 노드는 다음으로 큰 값을 가질 수 있습니다. node_i의 경우 next_larger(node_i)는 j> i, node_j.val> node_i.val 및 j가 가능한 가장 작은 선택인 node_j.val입니다. 이러한 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 ]