实验四 顺序队列、链队列(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());