Skip to content

栈队列算法

队列

FIFO: First in, First out(先进先出)

/**
* Queue FIFO
**/
class Queue {
  constructor() {
    this.dataSource = [];
  }

  enqueue(el) {
    this.dataSource.push(el);
  }

  dequeue(el) {
    this.dataSource.shift(el);
  }

  front() {
    return this.dataSource[0];
  }

  back() {
    return this.dataSource[this.dataSource.length-1];
  }

  clear() {
    this.dataSource = [];
  }
}

/* stack LIFO */
// LIFO: Last in, First out(后进先出)
class Stack {
  constructor() {
    this.dataSource = [];
    this.top = 0;
  }

  push(el) {
    this.dataSource[this.top++] = el;
  }

  pop() {
    return this.dataSource[--this.top]
  }

  peek() {
    return this.dataSource[this.top-1]
  }

  clear() {
    this.dataSource = [];
  }

}

Last update: July 15, 2024