<!DOCTYPE html>
<html>
<head>
<title>queue</title>
<meta charset="utf-8">
<script type="text/javascript">
function Queue(){
// 用于存储队列的数据结构
var items = [];
// enqueue:向队列末尾添加一个或多个新的项
this.enqueue = function(element){
items.push(element);
};
// dequeue:移除队列的第一项,并返回被移除的元素
this.dequeue = function(){
items.shift();
};
// front:返回队列中的第一个元素
this.front = function(){
return items[0];
};
// isEmpty:如果队列中不包含任何元素,返回true,否则返回false
this.isEmpty = function(){
return items.length == 0;
};
// clear:清空队列
this.clear = function(){
items = [];
};
// size:返回队列中包含的元素个数,与数组的length方法类似
this.size = function(){
return items.length;
};
// print:打印队列元素
this.print = function(){
console.log(items.toString());
};
}
// 队列的使用
// 创建队列
var queue = new Queue();
console.log(queue.isEmpty()); //输出true
// 给队列添加元素
queue.enqueue("John");
queue.enqueue("Jack");
queue.enqueue("Alice");
// 打印队列
queue.print(); //输出 John,Jack,Alice
// 输出队列大小
console.log(queue.size()); //输出 3
// 删除队列元素
queue.dequeue();
// 打印队列
queue.print(); //输出 Jack,Alice
</script>
</head>
<body>
</body>
</html>