0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

キュー実装編 step 1

0
Posted at

今回は paiza の「キュー実装編 step 1」の問題に挑戦!


🟦 問題概要

🔹 テーマ

  • キュー(FIFO) を実装する問題
  • FIFO = First In, First Out(先入れ先出し)

🔹 やること

  • 空の配列 A を用意
  • Q 個のクエリを順番に処理
  • 各クエリ処理後に、配列の中身を出力

🔹 クエリの種類

1 X

  • X を 配列の末尾に追加
    → PUSH 操作

2

  • 配列の 先頭を削除
    → POP 操作

🔹 出力ルール

  • 各クエリの処理後に出力
  • 要素は 半角スペース区切り
  • 余計な空白や空行は禁止
  • 行数は Q

🔹 入力構造

Q
query1
query2
...
queryQ

🔹 条件

  • Q < 100(小さい)
  • POP のときは必ず要素が存在
    → エラーチェック不要



入力例:

4
1 1
1 4
1 2
2

出力例:

1
1 4
1 4 2
4 2






✅OK例:

const rl = require('readline').createInterface({ input: process.stdin });

const lines = [];
rl.on('line', line => lines.push(line));

rl.on('close', () => {
    const Q = Number(lines[0]);
    const query = lines.slice(1).map(q => q.split(' ').map(Number));
    
    const arrA = [];
    
    for (let i = 0; i < Q; i++) {
        const [num, x] = query[i];
        
        if (num === 1) {
            arrA.push(x);
        } else {
            arrA.shift();
        }
        
        console.log(arrA.join(' '));
    }
});

🔍コードの流れ

  • readline で標準入力を受け取る準備
  • 入力を lines 配列に全部保存
  • 入力が終わったら(close イベント)
    • 1行目を Q(クエリ数)として取得
    • 2行目以降を数値配列に変換して query に格納
    • 空配列 arrA を用意(キュー)
    • Q 回ループしてクエリ処理
      • 1 Xpush(X)(末尾に追加)
      • 2shift()(先頭を削除)
      • 処理後の配列を join(' ') で出力






📝まとめ

🔹 ① キューとは

  • 先に入れたものが先に出る
  • イメージ:レジの列

🔹 ② JavaScriptでの実装

  • 末尾に追加:push()
  • 先頭を削除:shift()
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?