พิจารณาคลาสสแต็กอย่างง่ายใน 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 หรือไม่ ฟังก์ชัน Push ใช้เพื่อเพิ่มองค์ประกอบใหม่ลงในสแต็ก
ในส่วนนี้ เราจะเพิ่มการดำเนินการ POP ในคลาสนี้ การเปิดองค์ประกอบจาก Stack หมายถึงการลบออกจากด้านบนของอาร์เรย์ เรากำลังทำให้ส่วนท้ายของคอนเทนเนอร์อาร์เรย์อยู่ด้านบนสุดของอาร์เรย์ เนื่องจากเราจะดำเนินการทั้งหมดในส่วนที่เกี่ยวกับอาร์เรย์นั้น ดังนั้นเราจึงสามารถใช้ฟังก์ชันป๊อปได้ดังนี้ −
ตัวอย่าง
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 ]