พิจารณาคลาสสแต็กอย่างง่ายใน 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();
}
} ที่นี่ เต็มแล้ว ฟังก์ชั่นเพียงตรวจสอบว่าความยาวของคอนเทนเนอร์เท่ากับหรือมากกว่า maxSize และส่งคืนตามนั้น ว่างเปล่า ฟังก์ชันตรวจสอบว่าขนาดของคอนเทนเนอร์เป็น 0 หรือไม่ ฟังก์ชัน Push และ Pop ใช้เพื่อเพิ่มและลบองค์ประกอบใหม่ออกจากสแต็กตามลำดับ
ในส่วนนี้ เราจะเพิ่มการดำเนินการ PEEK ในคลาสนี้ Peeking a Stack หมายถึงการรับค่าสูงสุดของอาร์เรย์ ดังนั้นเราจึงสามารถใช้ฟังก์ชัน 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