LoginSignup
0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 スタック・キューメニュー JavaScript スタック実装編

Posted at

スタック実装編 step 1 (paizaランク C 相当)

スタックから要素を削除するプログラムを実装します。

解答例

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [Q] = lines[0].split(" ").map(Number);

//空の配列A
let A = [];

//クエリを順に処理
for (let i = 1; i <= Q; i++) {
  const [query, X] = lines[i].split(" ");
  if (query === "1") {
    A.push(X);
  } else {
    A.pop();
  }
  //各クエリの処理が終わったあと、配列 A の各要素の値を半角スペース区切りで出力
  console.log(A.join(" "));
}

FINAL問題 スタック実装編 step 2(paizaランク C 相当)

スタックを完成させます。

解答例

pop()は配列の末尾にある要素を返します。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [Q] = lines[0].split(" ").map(Number);

//空の配列A
let A = [];

//クエリを順に処理
for (let i = 1; i <= Q; i++) {
  const [query, X] = lines[i].split(" ");
  if (query === "1") {
    A.push(X);
  } else {
    console.log(A.pop());//末尾を削除して出力
  }
  //各クエリの処理が終わったあと、配列 A の各要素の値を半角スペース区切りで出力
  console.log(A.join(" "));
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0