พิจารณาคลาส Stack พร้อมฟังก์ชันช่วยใน JavaScript
ตัวอย่าง
class Stack {
constructor(maxSize) {
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
this.container = [];
}
display() {
console.log(this.container);
}
isEmpty() {
return this.container.length === 0;
}
isFull() {
return this.container.length >= maxSize;
}
}
isFull ตรวจสอบความยาวเท่าหรือเกิน maxSize, isEmpty ตรวจสอบความยาวเป็น 0
เพิ่มการทำงาน PUSH: เพิ่มสมาชิกที่บนสุด (ใช้ปลายอาร์เรย์เป็น top)
ตัวอย่าง
push(element) {
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
ทดสอบ:
ตัวอย่าง
let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();
ผลลัพธ์
จะได้ผลลัพธ์:
[] Stack Overflow! [ 10, 20 ]