티스토리 뷰

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

 

10828번: 스택

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

www.acmicpc.net

 

출력. console.log 때문에 시간초과가 발생했다. 

console.log로 한번에 출력하는 연습을 해야겠다. 

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


class Node{
    constructor(item){
      this.item = item;
      this.next = null;
    }
  }
  
  class Stack{
    constructor(){
      this.topOfStack = null;
      this.length = 0;
    }
  
    push(item){
      const node = new Node(item);
      if(this.topOfStack!=null){
        node.next = this.topOfStack; 
      }
        this.topOfStack = node;
        this.length+=1;
    }
  
    pop(){
      if(this.length==0)return -1;
      const popItem = this.topOfStack;
      this.topOfStack = popItem.next;
      this.length-=1;

      return popItem.item
    }
  
    size(){
      return this.length;
    }
  
    empty(){
      if(this.length==0) return 1;
      else return 0;
    }
  
    top(){
      if(this.length==0)return -1;
      return this.topOfStack.item; 
    }
  
  }


let answer = [];
let stack = new Stack(); 
const command = arr.map(v=>v.split(' '));
command.forEach(v=>{
    switch(v[0]){
        case 'push':
            stack.push(v[1])
            break;
        case 'pop':
            answer.push(stack.pop());
            break;
        case 'size':
            answer.push(stack.size())
            break;
        case 'empty':
            answer.push(stack.empty())
            break;
        case 'top':
            answer.push(stack.top())
            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
글 보관함