Javascript의 간단한 스택 클래스를 고려하십시오.
예시
class Stack {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
// A method just to see the contents while we develop this class
display() {
console.log(this.container);
}
// Checking if the array is empty
isEmpty() {
return this.container.length === 0;
}
// Check if array is full
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
} 여기 isFull이 있습니다. 함수는 컨테이너의 길이가 maxSize 이상인지 확인하고 그에 따라 반환합니다. 비어 있음 함수는 컨테이너의 크기가 0인지 확인합니다. 푸시 및 팝 함수는 스택에서 새 요소를 각각 추가 및 제거하는 데 사용됩니다.
이 섹션에서는 이 클래스에 PEEK 작업을 추가합니다. 스택 엿보기는 배열의 최상위 값을 가져오는 것을 의미합니다. 따라서 다음과 같이 엿보기 기능을 구현할 수 있습니다. -
peek() {
if (isEmpty()) {
console.log("Stack Underflow!");
return;
}
return this.container[this.container.length - 1];
} −
를 사용하여 이 기능이 제대로 작동하는지 확인할 수 있습니다.예시
let s = new Stack(2); s.peek(); s.push(10); console.log(s.peek());
출력
이것은 출력을 줄 것입니다 -
Stack Underflow! 10