JavaScript data structures [series] 03- queue Queue

JavaScript data structures [series] 03- queue Queue

Road workers CoderMonkey code
reproduced, please indicate the author and source

1. Understanding queue Queue structures

Queue, with our daily lives very close, we have an example in front of the cafeteria line up Dafan example, we continue to use this example to illustrate.

image.png

As shown in FIG,

  • The first queue is a queue head added
  • Finally, a tail of the queue
  • FIFO: FIFO, the backward-out principle
  • Add delete operations: only be added to the tail, only delete the queue head

Go to the bank to do business must first take a number and wait for call number, the same as the same.
(Banks also have VIP, we are talking about behind priority queue)

2. Application of the queue

  • JavaScript event queue
  • First traversal using a queue in FIG.
  • Print job queue when printing

Wait.

3. The realization of the queue

Note:
ES6 version code implements check out npm package data-struct-js code is
on Github / Gitee can be found

npm install data-struct-js

3.1 common method

And more similar stack

method description
enqueue(element) Add an element to the queue
dequeue() Delete queue element
front() View the current head of the queue elements
isEmpty() Check whether the queue is empty
size() Check queue capacity
clear() Clear the queue
toString() Stringified

3.2 The method used codes

Queue is a linear structure, let's look at it based on arrays to implement a common method.

First, write the constructor of Queue

function Queue() {
  this.__items = []
}

3.2.1 enqueue

Achieve Analysis:
add an element to the queue with a push

function Queue() {
  this.__items = []
  
  Queue.prototype.enqueue = function (element) {
      return this.__items.push(element)
  }
}

3.2.2 dequeue

Achieve Analysis:
delete queue row header element with shift

function Queue() {
  this.__items = []
  
  Queue.prototype.dequeue = function () {
    return this.__items.shift()
  }
}

3.2.3 front

Achieve Analysis:
View head of the queue that is the first element of the array

function Queue() {
  this.__items = []
  
  Queue.prototype.front = function () {
    return this.__items.length === 0 ? undefined : this.__items[0]
  }
}

3.2.4 isEmpty

Achieve Analysis:
just look at the number of array elements is zero internal

function Queue() {
  this.__items = []
  
  Queue.prototype.isEmpty = function () {
      return __items.length === 0
  }
}

3.2.5 size

Analysis achieved:
returns the number of interior array elements

function Queue() {
  this.__items = []
  
  Queue.prototype.size = function () {
      return this.__items.length
  }
}

3.2.6 clear

Achieve Analysis:
just look at the number of elements is 0

function Queue() {
  this.__items = []
  
  Queue.prototype.clear = function () {
      this.__items.length = 0
  }
}

3.2.7 toString

Achieve Analysis:
The internal array with the join link

function Queue() {
    this.__items = []
  
  Queue.prototype.toString = function() {
    return this.__items.join(',')
  }
}

Complete code:

function Queue() {
  this.__items = []

  Queue.prototype.enqueue = function (element) {
    this.__items.push(element)
  }

  Queue.prototype.dequeue = function () {
    return this.__items.shift()
  }

  Queue.prototype.front = function () {
    return this.__items.length === 0 ? undefined : this.__items[0]
  }

  Queue.prototype.isEmpty = function () {
    return this.__items.length === 0
  }

  Queue.prototype.size = function () {
    return this.__items.length
  }

  Stack.prototype.clear = function () {
    this.__items.length = 0
  }

  Queue.prototype.toString = function () {
    return this.__items.join(' ')
  }
}

3.3 Let's test

// ---------------------------------------------
// Test: Queue
// ---------------------------------------------
var q = new Queue()
for (var i = 0; i < 5; i++) {
    q.enqueue(i)
}
console.log('isEmpty: ', q.isEmpty())
console.log('size: ', q.size())
console.log('toString: ', q.toString())
while (!q.isEmpty()) {
    console.log(`dequeue: `, q.dequeue())
}
console.log('isEmpty: ', q.isEmpty())
console.log('size: ', q.size())

// 打印结果:
// isEmpty:  false
// size:  5
// toString:  0 1 2 3 4
// dequeue:  0
// dequeue:  1
// dequeue:  2
// dequeue:  3
// dequeue:  4
// isEmpty:  true
// size:  0

We got a result in line with expectations.

4. Questions: Based queue stack structure

The order of 4.1 stack and queue the principle is reversed, how to achieve the above queue with a stack?

Finished school Stack and Queue typical for these two data structures,
let us temporarily slow down climbing, slowly digest:
this time it just right to practice, to deepen understanding of these two data structures in use,
find us Code implementation, but also what issues, what needs to be improved.

Before answer, let us first slight improvement over the previous stack.

Recall that the stack structure of our common method of realization, what is still lacking?

  • You can not acquire elements of the collection
  • There is no way through the collection

4.1.1 Improved stack structure has been implemented

  • Method of adding elements of the set get

    Stack.js

function Stack() {
  this.__items = []
  // ...
  Stack.prototype.getItems = function() {
    return this.__items
  }
}

This is achieved, however,
there is no problem in a simple return __items a time when the transfer type,
when complex types, return of the external reference can be modified,
which do not meet the requirements of our stack.

// 错误结果示例:
var s = new Stack()
s.push(22)
s.push(33)
console.log(s)              // => [22, 33]
var items = s.getItems()
items[0] = 11
console.log(s)              // => [11, 33]
// ↑ 栈结构的数据不应该被这样修改
  • Gets Improved collection of elements
    here should use a deep copy, let's look at a simple implementation of
    this method has accumulated more than a tool you can write your own library of tools
// 工具方法:深拷贝
function deepCopy(source) {
  var dest
  if(Array.isArray(source)) {
    dest = []
    for (let i = 0; i < source.length; i++) {
      dest[i] =deepCopy(source[i])
    }
  }
  else if(toString.call(source) === '[object Object]') {
    dest = {}
    for(var p in source){
      if(source.hasOwnProperty(p)){
        dest[p]=deepCopy(source[p])
      }
    }
  }
  else {
    dest = source
  }
  return dest
}

Stack.js

Stack.prototype.getItems = function() {
  this.__items = []
  // ...
  Stack.prototype.getItems = function() {
    return deepCopy(this.__items)
  }
}

have a test:

// 正确结果示例:
var s = new Stack()
s.push(22)
s.push(33)
console.log(s)              // => [22, 33]
var items = s.getItems()
items[0] = 11
console.log(s)              // => [22, 33]
// ↑ 栈结构的数据未被修改
  • Through the collection

    Stack.js

When using this method to traverse getItems just added above, a copy of the incoming set of elements within the callback

Stack.prototype.traverse = function (cb) {
  if (!cb || toString.call(cb) !== '[object Function]') return

  var items = this.getItems()
  for (var index = items.length - 1; index >= 0; index--) {
    var element = items[index];
    cb(element, index)
  }
}

Similarly, you can add more than two methods to queue Queue
(getItems method to obtain a collection of methods and traverse traverse),
you can try it

Next, we went to queue to achieve complete stack-based structure.

4.2 code implementation

Achieve Analysis: The
sequence of stack and queue the principle is exactly the opposite, use the stack queue, you need two stacks,
an incoming element release, a release order to prepare the team after adjusting elements.

  • __inStack : For the team
  • __outStack : For the team
  • When the team: directly into the team, push into__inStack 
  • When the team: the team the collection __outStackhas elements directly out of the team, if not the __inStack elements in the reverse
function QueueBasedOnStack() {

  this.__inStack = new Stack()
  this.__outStack = new Stack()

  QueueBasedOnStack.prototype.enqueue = function(element) {
    this.__inStack.push(element)
  }

  QueueBasedOnStack.prototype.dequeue = function() {
    if(this.__outStack.isEmpty()) {
      while(!this.__inStack.isEmpty()) {
        this.__outStack.push(this.__inStack.pop())
      }
    }
    return this.__outStack.pop()
  }

  QueueBasedOnStack.prototype.size = function() {
    return (this.__inStack.size() + this.__outStack.size())
  }

  QueueBasedOnStack.prototype.isEmpty = function() {
    return this.__inStack.size() === 0 && this.__outStack.size() === 0
  }

  QueueBasedOnStack.prototype.clear = function() {
    this.__inStack.clear() 
    this.__outStack.clear()
  }

  QueueBasedOnStack.prototype.toString = function() {
    var items = this.getItems()
    return items.join('--')
  }

  QueueBasedOnStack.prototype.getItems = function() {
    return this.__inStack.getItems().concat(this.__outStack.getItems().reverse())
  }
}

have a test

// ---------------------------------------------
// Test: QueueBasedOnStack
// ---------------------------------------------
console.log('----Test: QueueBasedOnStack----')

var qs = new QueueBasedOnStack()
qs.enqueue('A')
console.log('after enqueue: ', qs.toString())
qs.enqueue('B')
console.log('after enqueue: ', qs.toString())
qs.enqueue('C')
qs.enqueue('D')
qs.enqueue('E')
console.log('after enqueue: ', qs.toString())
qs.dequeue()
console.log('after dequeue: ', qs.toString())
qs.dequeue()
console.log('after dequeue: ', qs.toString())
qs.dequeue()
console.log('after dequeue: ', qs.toString())

View Results:

----Test: QueueBasedOnStack----
after enqueue:  A
after enqueue:  A--B
after enqueue:  A--B--C--D--E
after dequeue:  B--C--D--E
after dequeue:  C--D--E
after dequeue:  D--E

knock off.


Npm do a toolkit data-struct-js,
based on JavaScript data structures ES6 implemented,
although the small wheels rarely used,
perhaps for beginners to learn JavaScript will be a little help.
Simply install what you can, interested can also go to
GitHub / Gitee look at the source code. (Star Table support ~)

npm install data-struct-js --save-dev

https://github.com/CoderMonkie/data-struct-js
https://gitee.com/coder-monkey/data-struct-js

Finally, thank you for reading and support ~


-end-

Guess you like

Origin www.cnblogs.com/CoderMonkie/p/js-data-struct-queue.html