티스토리 뷰

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

 

10866번: 덱

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

www.acmicpc.net

const fs = require('fs');
const [n, ...arr] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");



class Node{
    constructor(item){
      this.item = item;
      this.prev = null;
      this.next = null;
    }
  }
  
  class Deque{
    constructor(){
      this.head = null;
      this.tail = null;
      this.length = 0;
    }
  
    push_front(item){
      const node = new Node(item);
     if(this.size()==0){
       this.head = node;
       this.tail = node;
     }else{
      this.head.prev = node;
      node.next=this.head;
      this.head = node;
     }
      this.length+=1; 
    }
  
  
    push_back(item){
      const node = new Node(item)
      if(this.size()==0){
        this.head = node;
        this.tail = node;
      }else{
        this.tail.next = node;
        node.prev = this.tail;
        this.tail = node; 
      }
      this.length +=1;
    }
  
    pop_front(){
      if(this.size()==0) return -1;
      const popItem = this.head;
      this.head = this.head.next;
      if(this.size()==1){
          this.head = null;
      }else{
          this.head.prev = null;
      }
      this.length -=1;
      return popItem.item;
    }
  
    pop_back(){
      if(this.size()==0) return -1;
      const popItem = this.tail;
      this.tail = this.tail.prev;
      if(this.size()==1){
          this.tail = null;
      }else{
          this.tail.next = null;
      }
      this.length -=1;
      return popItem.item;
    }
  
  
    size(){
      return this.length;
    }
  
    empty(){
      if(this.length==0){
        return 1;
      }else{
        return 0;
      }
    }
  
    front(){
      if(this.empty()==1) return -1;
      return this.head.item; 
    }
  
    back(){
      if(this.empty()==1) return -1;
      return this.tail.item; 
    }
  }


let answer = [];
let deque = new Deque(); 
const command = arr.map(v=>v.split(' '));
command.forEach(v=>{

    switch(v[0]){
        case 'push_front':
            deque.push_front(v[1])
            break;
        case 'push_back':
            deque.push_back(v[1])
            break;
        case 'pop_front':
            answer.push(deque.pop_front());
            break;
        case 'pop_back':
            answer.push(deque.pop_back());
            break;
        case 'size':
            answer.push(deque.size())
            break;
        case 'empty':
            answer.push(deque.empty())
            break;
        case 'front':
            answer.push(deque.front())
            break;
        case 'back':
            answer.push(deque.back())
            break;
    }
})

console.log(answer.join('\n'))
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
29 30
글 보관함