[DAY 26] Queue using Two Stacks
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 x: Enqueue element x into the end of the queue.
- 2: Dequeue the element at the front of the queue.
- 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()으로 분리하여 넣어줌