JavaScript 中队列的实现


以下是使用 JavaScript 来实现队列的代码。

示例

 实时演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   button {
      padding: 6px;
      margin: 4px;
   }
</style>
</head>
<body>
<h1>Implementation of queue in JavaScript.</h1>
<div class="result"></div>
<br />
<input type="text" class="enqueueVal" /><button class="enqueueBtn">
Enqueue
</button>
<button class="dequeueBtn">Dequeue</button>
<button class="Btn">Display</button>
<h3>Click on the above buttons to perform queue operations</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let enqueueBtnEle = document.querySelector(".enqueueBtn");
   let dequeueBtnEle = document.querySelector(".dequeueBtn");
   class Queue {
      constructor() {
         this.items = [];
         this.length = 0;
      }
   }
   Queue.prototype.enqueue = function (ele) {
      this.items[this.length] = ele;
      this.length += 1;
   };
   Queue.prototype.dequeue = function () {
      debugger;
      if (this.length === 0) {
         return "Underflow: no more elements to remove";
      }
      tempNum = this.items[0];
      this.length -= 1;
      return tempNum;
   };
   Queue.prototype.display = function () {
      debugger;
      if (this.length == 0) {
         return "Stack is empty";
      }
      for (let i = 0; i < this.length; i++) {
         resEle.innerHTML += this.items[i] + " , ";
      }
   };
   let queue1 = new Queue();
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "";
      queue1.display();
   });
   enqueueBtnEle.addEventListener("click", () => {
      let ele = document.querySelector(".enqueueVal").value;
      resEle.innerHTML = ele + " is added to the back of the queue";
      queue1.enqueue(ele);
   });
   dequeueBtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      queue1.dequeue() + " is removed from the front of queue";
   });
</script>
</body>
</html>

输出

在输入一些值并单击“入队”按钮时 −

在单击“出队”按钮时 −

在队列不为空时单击“显示”按钮时 −

更新于: 20-Jul-2020

263 次浏览

开启你的 职业生涯

完成课程并获得认证

开始
广告