在 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