"Data Structure - Queue"

A queue is different from a stack. A stack is last in, first out, while a queue is first in, first out. It's like queuing up to buy breakfast, the front ones go first, and the back ones continue to wait. The ones added are at the end of the queue, and those to be deleted are at the head of the queue. Without further ado, let's create a queue.

First build the skeleton function queue( ){ }

Then create an array to store the elements of the queue var arr=[ ];

In fact, the method of queue is very similar to the method of stack, but the principle of deleting and adding elements is different. Now let's take a look at some methods of queue

1. enqueue(Element) adds one or more elements to the end of the queue

2. dequeue(Element) deletes the first element of the queue and returns the element

3. front() returns the first element of the queue without modifying the queue

4. isEmpty() judges whether the queue is empty, if it is, it returns true, otherwise it returns false

5. size() returns the number of elements in the queue

Well, the methods are introduced, let's improve these methods

1、this.enqueue=function(element){

   arr.push(element)

    }

2、this.dequeue=function(element){

  return  arr.pop(element)

  }

3、this.front=funtion(){

  return arr[0]

  }

4、this.isEmpty=function(){

  return arr.length==0

  }

5、this.size=funtion(){

  return arr.length

  }

Now that the method is complete, it's time to put them into the skeleton. These methods can then be called.

var fn = new queue ()

fn.enqueue() and other methods

We will continue to introduce the priority queue later.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325270626&siteId=291194637