在 JavaScript 中建立棧
在本文中,我們將討論如何在 JavaScript 中建立棧資料結構。它是一種線性資料結構,其中元素的入棧和出棧遵循 LIFO(後進先出)和 FILO(先進後出)順序。
儘管 JavaScript 中的陣列提供了棧的所有功能,但讓我們實現我們自己的棧類。我們的類將具有以下函式。
- push(element) − 用於將元素推入棧頂的函式。
- pop() − 從棧頂移除一個元素並返回它的函式。
- peek() − 返回棧頂的元素。
- isFull() − 檢查是否達到了棧上的元素限制。
- isEmpty() − 檢查棧是否為空。
- clear() − 移除所有元素。
- display() − 顯示陣列的所有內容
讓我們從定義一個簡單的類開始,該類帶有一個建構函式,該建構函式獲取棧的最大大小,以及一個輔助函式 display(),它將在我們為該類實現其他函式時提供幫助。我們還定義了另外兩個函式 isFull 和 isEmpty 來檢查棧是否已滿或為空。
isFull 函式只是檢查容器的長度是否等於或大於 maxSize,並相應地返回。
isEmpty 函式檢查容器的大小是否為 0。
這在定義其他操作時將很有用。從現在開始,我們定義的函式都將在 Stack 類中。
示例 1
以下示例演示瞭如何在 JavaScript 中建立棧資料結構。在此示例中,我們將討論 push() 和 pop() 方法的使用。我們建立一個棧並將元素新增到其中,並顯示棧元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Creating Stack Data Structure</title>
</head>
<body>
<script type="text/javascript">
class Stack {
constructor() {
this.stkArr = [];
}
// add element to the stack
add(element) {
return this.stkArr.push(element);
}
// remove element from the stack
remove() {
if (this.stkArr.length > 0) {
document.write("<br>");
return "The Popped element is : " + this.stkArr.pop();
}
}
// view the last element
peek() {
document.write("<br>");
return (
"The Peek element of the stack is : " +
this.stkArr[this.stkArr.length - 1]
);
}
// check if the stack is empty
isEmpty() {
document.write("<br>");
return this.stkArr.length == 0;
}
// the size of the stack
size() {
document.write("<br>");
return "The size of the stack is : " + this.stkArr.length;
}
display() {
if (this.stkArr.length !== 0) {
return "The stack elements are : " + this.stkArr + "<br>";
} else {
document.write("The Stack is Empty..! <br>");
}
}
// empty the stack
clear() {
document.write("
The stack is cleared..!" + "<br>");
this.stkArr = [];
}
}
let stack = new Stack();
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
document.write(stack.display());
document.write(stack.size());
</script>
</body>
</html>
示例 2
另一個在 JavaScript 中執行棧操作的示例如下所示:
class Stack {
constructor(maxSize) {
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
this.container = [];
}
display() {
console.log(this.container);
}
push(element) {
this.container.push(element);
}
}
const obj = new Stack(10);
obj.push(10);
obj.push(44);
obj.push(55);
obj.display();
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP