JavaScript模拟栈和队列数据结构

JavaScript模拟栈和队列数据结构

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太阳与星辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值