JS数据结构-队列

队列:数据结构

 存在两个指针,头指针:front 尾指针:rear

初始状态:

输入过程中:

输出过程:(未画)

方法:     输出: 头指针进行输入

                输入:尾指针后添加

<!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>Document</title>
</head>

<body>
</body>
<script>
  //队列的模拟 数据的结构
  // 队列的特点,先入,先出,有输入,有弹出,弹出的时候,是弹出的那个指。
  function Queue() {
    //节点类型
    const node = function (ele) {
      this.ele = ele;
      this.next = null;
    }
    //初始化长度;
    this.length = 0;
    //有两个指针: 头指针,尾指针
    this.front = null;
    this.rear = null;
    //添加节点。
    //两种情况:
    //第一种情况:头指针,尾指针指向第一个节点 此刻长度为0;
    //第二种情况,长度大于0,头指针不一定,尾指针移动。
    this.push = function (ele) {
      // 就需要创建一个节点:
      let newnode = new node(ele);
      if (this.length == 0) {
        //头指针,尾指针都指向了第一个节点。
        this.front = newnode;
        this.rear = newnode;
        this.length++;
      }
      //此刻数组的长度大于0了
      else if (this.length > 0) {
        this.rear.next = newnode;
        this.rear = newnode;
        this.length++;
      }
    }
    //队列的输出,
    this.pop = function () {
      if (this.length == 0) {
        console.log("当前队列为空,不能进行输出了");
        this.rear = null;
        return
      }
      //记录最前面的节点
      let temp = this.front;
      this.front = temp.next;
      this.length--;
      temp.next = null;
      if (this.length == 0) {
        //此刻是空了,需要将尾指针置空
        this.rear = null;
      }
      return temp;
    }
    //结果进行存储
    this.result = function () {
      let result = [];
      let flag = this.front
      if (!flag) {
        console.log(flag);
        return
      }
      //遍历了单链表
      while (flag) {
        result.push(flag);
        flag = flag.next;
      }
      return result;
    };
  }

  const queue = new Queue();
  // queue.push(1);
  // queue.push(2);
  // queue.pop();
  // console.log(queue.front);
  // console.log(queue.rear);
  // console.log(queue.length);

</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值