본문 바로가기
Web development/Algorithm

[javascript] 큐, 스택 구현

by 자몬다 2020. 7. 8.

큐 구현

// 큐
const q = [];
const push = (item) => q.push(item);
const pop = () => q.pop();

q.push(1);
console.log(q); // [ 1 ]
q.push(2);
console.log(q); // [ 1, 2 ]
q.push(3);
console.log(q); // [ 1, 2, 3 ]
q.pop();
q.pop();
q.push(4);
console.log(q); // [ 1, 4 ]

 

 

스택 구현

// 스택
const stack = [];
const push = (item) => stack.push(item);
const shift = () => stack.shift();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack); // [ 1, 2, 3 ]
stack.shift();
stack.shift();
console.log(stack); // [ 3 ]
stack.push(4);
stack.push(5);
stack.shift();
stack.shift();
console.log(stack); // [ 5 ]

 

 

댓글