数据结构-队列
队列
- 队列是先进先出的线性表,在具体应用中通常用链表或者数组来实现。
链表实现队列
import LinkedList from '../linked-list/LinkedList';
// 链表实现队列
export default class Queue {
constructor() {
this.linkedList = new LinkedList();
}
isEmptey() {
return !this.linkedList.tail;
}
enqueue(value) {
this.linkedList.append(value);
}
dequeue() {
const removeHead = this.linkedList.deleteHead();
return removeHead ? removeHead.value : null;
}
toString(callback) {
return this.linkedList.toString(callback);
}
}
数组实现队列
export default class ArrayQueue {
constructor(capacity) {
this.n = capacity;
this.item = new Array(capacity);
this.head = 0;
this.tail = 0;
}
enqueue(value) {
// 队列已满
if (this.tail === this.n) {
if (this.head === 0) {
return false;
}
// 数据搬移
for (let i = this.head; i < this.tail; i++) {
this.item[i - this.head] = this.item[i];
}
// 更新tail head
this.tail -= this.head;
this.head = 0;
}
this.item[this.tail] = value;
this.tail = this.tail + 1;
return true;
}
dequeue() {
let value = '';
if (this.tail === this.head) return null;
value = this.item[this.head];
this.head = this.head + 1;
return value;
}
}
数组实现循环队列
// (tail+1)%n === head 满队列的条件
export default class CircleQueue {
constructor(capacity) {
this.n = capacity;
this.item = new Array(capacity);
this.head = 0;
this.tail = 0;
}
enqueue(value) {
if ((this.tail + 1) % this.n === this.head) {
return false;
}
this.item[this.tail] = value;
this.tail = (this.tail + 1) % this.n;
return true;
}
dequeue() {
if (this.head === this.tail) {
return null;
}
const value = this.item[this.head];
this.head = (this.head + 1) % this.n;
return value;
}
}
参考链接