Xét lớp Stack đơn giản:
Ví dụ - Lớp Stack cơ bản
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; } push(element) { if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); } }
Thêm thao tác POP: xóa phần tử đỉnh (cuối mảng container).
Ví dụ
pop() { if (this.isEmpty()) { console.log("Stack Underflow!"); return; } this.container.pop(); }
Kiểm tra:
Ví dụ
let s = new Stack(2); s.display(); s.pop(); s.push(20); s.push(30); s.pop(); s.display();
Kết quả
[] Stack Underflow! [ 20 ]
Pop stack rỗng báo Underflow. Push 20,30 rồi pop xóa 30, còn [20].