编辑代码

// 设置标准输入接口
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
  // 读取输入并将其分割为数字数组
  const arr = (await readline()).split(",").map(Number);
  // 初始化结果数组,默认值为 -1
  const res = Array.from({ length: arr.length }, () => -1);
  // 创建一个栈用于存储索引
  const stack = [];
  // 遍历数组两次以处理循环情况
  for (let i = 0; i < arr.length * 2; i++) {
    const idx = i % arr.length; // 当前索引
    // 当栈不为空且当前元素大于栈顶元素时,更新结果数组
    while (stack.length > 0 && arr[stack[stack.length - 1]] < arr[idx]) {
      const index = stack.pop(); // 弹出栈顶索引
      res[index] = arr[idx]; // 更新结果数组
    }
    stack.push(idx); // 将当前索引压入栈中
  }
  // 输出结果数组
  console.log(res.join(" "));
})();