1.模拟栈
//stack.js
class Stack {
constructor() {
this.items = [];
}
// 入栈操作
push(item) {
this.items.push(item);
}
// 出栈操作
pop() {
if (this.items.length === 0) {
return "Stack is empty"; // 或者可以选择抛出异常:throw new Error("Stack is empty");
}
return this.items.pop();
}
// 查看栈顶元素
peek() {
if (this.items.length === 0) {
return "Stack is empty"; // 或者可以选择抛出异常:throw new Error("Stack is empty");
}
return this.items[this.items.length - 1];
}
// 查看栈的长度
size() {
return this.items.length;
}
// 判断栈是否为空
isEmpty() {
return this.items.length === 0;
}
// 清空栈
clear() {
this.items = [];
}
}
测试一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<script src="stack.js"></script>
<script>
// 使用示例
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.peek()); // 输出: 2
console.log(stack.size()); // 输出: 2
console.log(stack.pop()); // 输出: 2(移除并返回2)
console.log(stack.peek()); // 输出: 1
</script>
</body>
</html>
2.模拟队列
class Queue {
constructor() {
//用数组模拟队列
this.queue = [];
}
//入队列
enQueue(element) {
this.queue.push(element);
}
//出队列
deQueue() {
return this.queue.shift();
}
//查看队列中的第一个元素
front() {
return this.queue[0];
}
//判断队列是否为空
isEmpty() {
return this.queue.length === 0;
}
//返回队列的长度
size() {
return this.queue.length;
}
//清空队列的内容
clear() {
this.queue = [];
}
//以字符串显示队列内容
print() {
return this.queue.toString();
}
}
测试一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<script src="queue.js"></script>
<script>
// 使用示例
const queue = new Queue();
console.log(queue);
console.log(queue.isEmpty()); // 输出: true
queue.enQueue(1);
queue.enQueue(2);
console.log(queue.size);
console.log(queue.isEmpty()); // 输出: false
</script>
</body>
</html>

2225

被折叠的 条评论
为什么被折叠?



