在 Javascript 中將元素推入棧中
考慮以下 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;
}
}在這裡,isFull 函式只檢查容器的長度是否等於或大於 maxSize,並相應返回。isEmpty 函式檢查容器的大小是否為 0。
在本節中,我們要在這個類中新增 PUSH 操作。將元素推入棧意味著將它們新增到陣列的頂部。我們認為容器陣列的末尾是陣列的頂部,因為我們將對其執行所有操作。因此,我們可以按如下方式實現 push 函式 −
示例
push(element) {
// Check if stack is full
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 ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP