js로 스택/큐 구현하기
2023. 6. 12. 15:11
인트로
집중이 안돼서 오랜만에 알고리즘 복습하는 시간이나 가져보았습니다.
클래스로 스택 구현
class Stack {
constructor() {
this.stackArr = [];
this.top = 0;
}
push(value) {
this.stackArr[this.top] = value;
this.top += 1;
return value;
}
pop() {
if(this.top === 0) {
console.log('배열이 비었습니다');
return null;
}
this.top -= 1;
return this.stackArr.pop();
}
getsize() {
return this.stackArr.length;
}
}
const stack = new Stack;
stack.push(1);
stack.push(2);
console.log(stack.stackArr); //[1,2]
console.log(stack.getsize()); //2
stack.pop();
console.log(stack.stackArr); //[1]
stack.pop();
console.log(stack.stackArr); //[]
stack.pop(); //배열이 비었습니다.
console.log(stack.getsize()); //0
클래스로 큐 구현
class Que {
constructor() {
this.head = 0;
this.tail = 0;
this.queArr = [];
}
isEmpty() {
return this.tail === this.head;
}
front() {
if(this.isEmpty()) {
console.log('큐가 비어있습니다');
return null;
}
return this.queArr[this.head];
}
back() {
if(this.isEmpty()) {
console.log('큐가 비어있습니다');
return null;
}
return this.queArr[this.tail-1];
}
enque(value) {
this.queArr[this.tail] = value;
this.tail++;
}
deque() {
if(this.isEmpty()){
console.log('큐가 비어있습니다');
return null;
}
const dequeValue = this.queArr[this.head];
this.head++;
return dequeValue;
}
getsize() {
return this.tail-this.head;
}
}
const que = new Que;
que.enque(2)
que.enque(1)
console.log(que.getsize()); //2
console.log(que.deque()); //2
// {head:1 tail:2}
console.log(que.getsize()); //1
console.log(que.deque()); //1
// {head:2 tail:2}
console.log(que.getsize()); //0
console.log(que.deque()); //큐가 비었습니다. null
프로그래머스에서 간단한 스택 문제도 하나 풀어봤습니다.
같은 숫자는 싫어
function solution(arr)
{
const copyArr = arr.slice();
var answer = [copyArr.pop()];
while (copyArr.length !== 0) {
const popValue = copyArr.pop();
if(answer[answer.length-1] !== popValue) {
answer.push(popValue);
}
}
return answer.reverse();
}