티스토리 뷰

1Day 1Algorithm

[DAY 26] Queue using Two Stacks

walk_through_me 2019. 10. 26. 12:19

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed.

A basic queue has the following operations:

  • Enqueue: add a new element to the end of the queue.
  • Dequeue: remove the element from the front of the queue and return it.

In this challenge, you must first implement a queue using two stacks. Then process q queries, where each query is one of the following 3 types:

  1. 1 x: Enqueue element x into the end of the queue.
  2. 2: Dequeue the element at the front of the queue.
  3. 3: Print the element at the front of the queue.
 

Queue using Two Stacks | HackerRank

Create a queue data structure using two stacks.

www.hackerrank.com

 

풀이

function processData(input) {
    let arr = input.split('\n');
    let len = arr[0]
    let q = [];
    for(let i = 1; i <= len; i++){
        switch(true) {
            case arr[i][0] == 1 : 
                q.push(arr[i].slice(2));
                break;
            case arr[i] == 2 :
                q.shift();
                break;
            case arr[i] == 3 : 
                console.log(q[0]);
                break;
        }
    }
} 

1. string으로 구성된 input을 줄바꿈 단위로 분리하여 배열로 만들어줌

2. 배열의 첫 값은 큐의 길이이므로 len 변수에 넣어줌

3. q라는 빈 배열을 생성

4. 1번 인덱스부터(0번은 큐 길이이므로) for문을 돌면서 switch 문을 사용하여 각 조건에 맞는 것을 실행해줌 → 1일 경우 1뒤에 있는 숫자를 q에 푸시, 2일 경우 shift()로 q에서 제거, 3일 경우 q의 첫번째 값을 출력

 

 

다른 사람의 풀이

function processData(input) { 
	const data = input.split("\n"); 
    const loops = data[0];

    const queue = [];

    for (let i = 1; i <= loops; i++) {
        const currentInput = data[i].split(" ");
        //console.log(currentInput)
        if (currentInput.length > 1) {
            if (currentInput[0] == 1) {
                queue.push(currentInput[1]);
            }
        } else {
            if (currentInput[0] == 2) {
                queue.shift();
            } else if (currentInput[0] == 3) {
                console.log(queue[0]);
            }
        }
    }
}

currentInput 변수를 만들어 "1  14"와 같이 공백이 들어가 있는 값을 한번더 split()으로 분리하여 넣어줌

'1Day 1Algorithm' 카테고리의 다른 글

[DAY 28] 문자열 내 p와 y의 개수  (0) 2019.10.29
[DAY 27] Truck tour  (0) 2019.10.27
[DAY 25] 비밀지도 (2018 KAKAO BLIND RECRUITMENT)  (0) 2019.10.26
[DAY 24] 약수의 합  (0) 2019.10.25
[DAY 23] 서울에서 김서방 찾기  (0) 2019.10.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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 31
글 보관함