JavaScript数据结构:队列

时间:2025-04-06 19:33:39
  • function Queue() {
  • //队头
  • this.head = null
  • //队尾
  • this.tail = null
  • //队的长度
  • this.length = 0
  • //节点
  • function Node(value) {
  • this.value = value
  • this.next = null
  • }
  • //入队
  • Queue.prototype.push = function (val) {
  • const node = new Node(val)
  • if (this.length === 0) {
  • //如果队列长度为0,队头和队尾都指向新插入节点
  • this.head = node
  • this.tail = node
  • } else {
  • //如果队列长度大于0,队尾的next指向新插入节点
  • this.tail.next = node
  • //队尾向后移动一位,指向新插入的节点
  • this.tail = this.tail.next
  • //移动后的队尾的next指向队头
  • this.tail.next = this.head
  • }
  • //插入完成,队列长度加1
  • this.length++
  • }
  • //出队
  • Queue.prototype.remove = function () {
  • //如果队列长度为0,返回null
  • if (this.length === 0) return null
  • else {
  • //要移除的队首的value
  • const value = this.head.value
  • if (this.length === 1) {
  • //当队列的长度为1时,出队后队列为空
  • //此时队首和队尾都为null
  • this.head = null
  • this.tail = null
  • } else if (this.length === 2) {
  • //当队列长度为2时,出队后,队列长度为1
  • //此时队头和队尾同时指向队尾节点,队尾节点的next指向null
  • this.tail.next = null
  • this.head = this.tail
  • } else {
  • //将队首向后移动一位
  • this.head = this.head.next
  • //队尾的next指向新的队首
  • this.tail.next = this.head
  • }
  • //完成出队,队列长度减一
  • this.length--
  • return value
  • }
  • }
  • //返回队头元素的值
  • Queue.prototype.front = function () {
  • //如果队列长度为0,返回null
  • if (this.length === 0) return null
  • //反之返回队头的value
  • return this.head.value
  • }
  • //判断队列是否为空
  • Queue.prototype.isEmpty = function () {
  • //直接判断队列的长度是否等于1
  • return this.length === 0
  • }
  • //获取队列的大小
  • Queue.prototype.size = function () {
  • //直接返回队列的长度
  • return this.length
  • }
  • }