How to implement queue structure in JavaScript
This article mainly explains "how to achieve the queue structure in JavaScript". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to realize the queue structure in JavaScript".
I. Cognition queue
The previous blog has talked about limited data structures-stacks, and now let's take a look at Queue.
It is a restricted linear table, first-in, first-out (FIFO), or first in first out.
The limitation is that it only allows deletions at the front end of the table (front).
The insert operation is performed at the back end of the table (rear).
Its structure diagram can be expressed as follows:
Life is similar to queues: for example, when we are waiting in line to buy something, we buy it on a first-come-first-served basis.
Second, encapsulation queue
Here, an array is also used to implement the queue structure. First, create a class.
Function Queue () {}
Add properties and methods inside it, and add the array to the class through the methods of properties. Then use the prototype method to add common operations.
The common operations of queues are:
Enqueue (element): add one (or more) new items to the end of the queue
Dequeue (): removes the first item in the queue (that is, the first item in the queue) and returns the removed element
Front (): returns the first element in the queue-the first to be added and will be the first to be removed
IsEmpty (): returns true if the queue does not contain any elements, otherwise returns false
Size (): returns the number of elements contained in the queue
ToString (): converts the contents of the queue into a string
Let's do it now:
Function Queue () {this.items = []; / add a new item enqueue () Queue.prototype.enqueue = function (element) {this.items.push (element) to the end of the queue;} / / remove the first item in the queue (that is, the first item in the queue) dequeue () Queue.prototype.dequeue = function () {return this.items.shift () } / / return the first element in the queue front () Queue.prototype.front = function () {return this.items [0];} / / determine whether the stack is empty isEmpty () Queue.prototype.isEmpty = function () {return this.items.length = = 0 } / / return the number of elements contained in the queue size () Queue.prototype.size = function () {return this.items.length;} / / convert the contents of the queue into the string form toString () Queue.prototype.toString = function () {var str =''; for (var I = 0Tring I