-
Notifications
You must be signed in to change notification settings - Fork 411
Queue
A queue is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue (or push), and removal of entities from the front terminal position, known as dequeue (or pop). This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed. Often a peek or front operation is also entered, returning the value of the front element without dequeuing it. A queue is an example of a linear data structure, or more abstractly a sequential collection.
Source: Wikipedia
Code: https://github.com/felipernb/algorithms.js/blob/master/data_structures/queue.js
Test: https://github.com/felipernb/algorithms.js/blob/master/test/data_structures/queue.js
var Queue = require('algorithms').DataStructure.Queue;
var q = new Queue();
Pushes an element to the back of the queue (O(1))
var q = new Queue();
q.push(1); // (1)<front
q.push(2); // (2)(1)<front
q.push(3); // (3)(2)(1)<front
Pops an element from the front of the queue (O(1))
var q = new Queue();
q.push(1); // (1)<front
q.push(2); // (2)(1)<front
q.push(3); // (3)(2)(1)<front
q.pop(); // 1
q.pop(); // 2
q.pop(); //3
Returns the element from the front of the queue, without removing it (O(1))
var q = new Queue();
q.push(1); // (1)<front
q.push(2); // (2)(1)<front
q.push(3); // (3)(2)(1)<front
q.peek(); // 1
q.peek(); // 1
q.pop(); // 1
q.peek(); // 2