dist-javascript-algorithms-and-data-structures
Version:
Algorithms and data-structures implemented on JavaScript
75 lines (58 loc) • 1.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _LinkedList = _interopRequireDefault(require("../linked-list/LinkedList"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Queue {
constructor() {
// We're going to implement Queue based on LinkedList since the two
// structures are quite similar. Namely, they both operate mostly on
// the elements at the beginning and the end. Compare enqueue/dequeue
// operations of Queue with append/deleteHead operations of LinkedList.
this.linkedList = new _LinkedList.default();
}
/**
* @return {boolean}
*/
isEmpty() {
return !this.linkedList.head;
}
/**
* Read the element at the front of the queue without removing it.
* @return {*}
*/
peek() {
if (!this.linkedList.head) {
return null;
}
return this.linkedList.head.value;
}
/**
* Add a new element to the end of the queue (the tail of the linked list).
* This element will be processed after all elements ahead of it.
* @param {*} value
*/
enqueue(value) {
this.linkedList.append(value);
}
/**
* Remove the element at the front of the queue (the head of the linked list).
* If the queue is empty, return null.
* @return {*}
*/
dequeue() {
const removedHead = this.linkedList.deleteHead();
return removedHead ? removedHead.value : null;
}
/**
* @param [callback]
* @return {string}
*/
toString(callback) {
// Return string representation of the queue's linked list.
return this.linkedList.toString(callback);
}
}
exports.default = Queue;