top
: 스택 맨 위의 데이터. 제일 나중에 들어온 데이터.push
: 스택 맨 위에 데이터 삽입pop
: 스택 맨 위의 데이터 삭제 및 삭제한 데이터 반환peek
: 스택 맨 위의 데이터를 반환하는 메서드stack overflow
: 스택 메모리보다 데이터를 더 넣었을 때 발생하는 오류stack underflow
: 스택에 메모리가 비어있는데 데이터를 꺼내려고 할 때 발생하는 오류let Stack = (function () {
function Stack() {
this.top = null; // 스택 맨 위의 데이터
this.count = 0;
}
function Node(data) {
this.data = data;
this.next = null; // 다음 노드를 가리킴
}
Stack.prototype.push = function (data) {
let node = new Node(data);
node.next = this.top;
this.top = node;
return ++this.count;
};
Stack.prototype.pop = function () {
if (!this.top) { // stack underflow 방지
return false;
}
let data = this.top.data;
this.top = this.top.next;
// 예전 this.top의 메모리 정리
this.count--;
return data;
}
Stack.prototype.peek = function () {
return this.top.data;
};
return Stack;
})();
let stack = new Stack();
stack.push(1);
stack.push(3);
stack.push(5);
console.log(stack.pop()); // 5
console.log(stack);
console.log(stack.peek()); // 3
console.log(stack.size()); // 2
클래스로 구현
class Stack {
constructor() {
this.top = null;
this.count = 0;
}
node(value) {
return {
value,
next: null,
};
}
push(value) {
const node = this.node(value);
if (this.top === null) {
this.top = node;
} else {
node.next = this.top;
this.top = node;
}
++this.count;
}
pop() {
if (this.count === 0) return;
let popped;
if (this.top && this.top.next) {
popped = this.top;
this.top = this.top.next;
} else {
popped = this.top;
this.top = null;
}
this.count--;
return popped.value;
}
peek() {
return this.top.value;
}
size() {
return this.count;
}
}
let stack = new Stack();
stack.push(1);
stack.push(3);
stack.push(5);
console.log(stack.pop()); // 5
console.log(stack);
console.log(stack.peek()); // 3
console.log(stack.size()); // 2
console.log(stack);
의 결과