티스토리 뷰

https://www.acmicpc.net/problem/10845

 

10845번: 큐

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n").map(v=>v.trim()); 
const answer = [];
const N = +input[0];
class Node {
  constructor(item) {
    this.item = item;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  push(item) {
    const node = new Node(item)
    if (this.head === null) {
      this.head = node;
      this.tail = node;
    } else {
      this.tail.next = node;
    }

    this.tail = node;
    this.length += 1;
  }

  pop() {
    if(this.length==0){
      return -1;
    }else{
      const popItem = this.head.item;
      this.head = this.head.next;
      this.length -= 1;
      return popItem;
    }
  }

  size(){
    return this.length;
  }

  empty(){
    if(this.length==0){
      return 1
    }else{
      return 0;
    }
  }

  front(){
    if(this.length==0){
      return -1;
    }else{
      return this.head.item
    }
  }

  back(){
    if(this.length==0){
      return -1;
    }else{
      return this.tail.item
    }
  }
}


let q = new Queue();

for(let i = 1; i <=N; i++){
  const command = input[i];
  switch(command){
    case 'front':
      answer.push(q.front())
      break;
    case 'back':
      answer.push(q.back())
      break;
    case 'size':
      answer.push(q.size())
      break;
    case 'empty':
      answer.push(q.empty())
      break;
    case 'pop':
      answer.push(q.pop())
      break;
    default:
      const [_,value] = command.split(' ');
      q.push(+value);
      break;
  }
}

console.log(answer.join('\n'))
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함