实验四  顺序队列、链队列(JavaScript)

实验四   顺序队列、链队列(JavaScript)


实验目的

熟练掌队列的结构特点,掌握队列的顺序存储和链式存储结构和实现。


实验内容

自己确定结点的具体数据类型和问题规模:

分别建立一个顺序队列和链队列,实现栈的入队和出队操作。


实验步骤

顺序队列

顺序队列是队列的顺序存储结构,类似于顺序表。

function StackSize(count) {
  this.arr = new Array();
  var rear = -1; //定义一个头指针
  var front = -1;
  if (count != undefined) {
    this.count = count;
    this.arr = new Array(this.count);
  } else {
    this.count = 0;
  }
//入队操作
  this.EnQueue = function (valve) {
    if (rear == this.count) {
      return false;
    } else {
      this.arr[++rear] = valve;
      return true;
    }
    return false;
  }
//显示队列
  this.Show = function () {
    for (var i = 0; i < this.arr.length; i++) {
      console.log(this.arr[i]);
    }
  }
//出队操作
  this.DeQueue = function () {
    if (front == rear) {
      return false;
    } else {
      front = front + 1;
      var remove = this.arr[front];
      this.arr[front] = null;
      front++;
      return remove;
    }
  }
}
//测试代码
StackSize(3);
this.EnQueue(1);
this.EnQueue(2);
this.EnQueue(3);
this.Show();
console.log("被删除的元素为:" + this.DeQueue());
this.Show();


链队列

链队列是在单链表的基础上做了简单的修改,为了使空队列和非空队列的从左一致,链队列也加上头结点。

function StackSize() {
    // this.arr = new Array();
    var length = 0;
    this.rear = null;
    this.front = null;
}

var List = function () {
    function Node(newdata) {
        this.data = newdata;
        this.next = null;
    }
//入队操作
    this.EnQueue = function (value) {
        var  node  =  new  Node(value),
                          current;            
        if (length  ==  0) {              
            this.front  =  node;              
            this.rear  =  node;              
            length++;                
            return  true;          
        } else {              
            current  =  this.rear;              
            current.next  =  node;              
            this.rear  =  node;              
            length++;                
            return  true; 
        }
    }

//取队列最后一个元素
    this.Getrear = function () {
        if (this.rear == null) {
            console.log("空队列");
        } else {
            return this.rear.data;
        }
    }
//出队操作
    this.DeQueue = function () {
        if (this.rear == this.front) {
            console.log("空队列");
        } else {
            var node = this.front;
            this.front = node.next;
            return node;
        }
    }
}
//测试代码
var list = new List();
list.EnQueue(1);
list.EnQueue(2);
list.EnQueue(3);
console.log(list.Getrear());
console.log(list.DeQueue());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值