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);
}
} 여기 가득함 함수는 컨테이너의 길이가 maxSize 이상인지 확인하고 그에 따라 반환합니다. 비어 있음 함수는 컨테이너의 크기가 0인지 확인합니다. 푸시 함수는 스택에 새 요소를 추가하는 데 사용됩니다.
이 섹션에서는 이 클래스에 POP 작업을 추가합니다. 스택에서 요소를 팝핑한다는 것은 배열의 맨 위에서 요소를 제거하는 것을 의미합니다. 모든 작업을 수행할 것이기 때문에 컨테이너 배열의 끝을 배열의 맨 위로 가져갑니다. 그래서 우리는 다음과 같이 pop 함수를 구현할 수 있습니다 -
예시
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
} 이 기능이 −
를 사용하여 제대로 작동하는지 확인할 수 있습니다.예시
let s = new Stack(2); s.display(); s.pop(); s.push(20); s.push(30); s.pop(); s.display();
출력
이것은 출력을 줄 것입니다 -
[] Stack Underflow! [ 20 ]