Js数据结构之栈与队列

学习编程已经有很长的时间了,虽然能独立的完成一些简单的项目,但在遇到一些难点的时候吗,仍感到自身算法方面的不足,所以特此记录自己学习数据结构与算法的过程。

1、栈结构

特点: 后进先出。

Js代码实现:

class Stack {
  constructor() {
    this.item = [];
  }
  push(val) {
    this.item.push(val);
  }
  pop() {
    return this.item.pop();
  }
  peek() {
    return this.item[this.item.length - 1];
  }
  isEmpty() {
    return this.item.length == 0;
  }
  size() {
    return this.item.length;
  }
  toString() {
    let result = '';
    for (let i = 0; i < this.item.length; i++) {
      result += this.item[i] + ' ';
    }
    return result;
  }
}

2、队列结构

1、一般队列

特点: 先进先出

Js代码实现:

class Queue {
  constructor() {
    this.item = [];
  }
  enqueue(val) {
    this.item.push(val);
  }
  dequeue() {
    return this.item.shift();
  }
  front() {
    return this.item[0];
  }
  isEmpty() {
    return this.item == 0;
  }
  size() {
    return this.item.length;
  }
  toString() {
    let result = '';
    for (let i = 0; i < this.item.length; i++) {
      result += this.item[i] + ' ';
    }
    return result;
  }
}

2、优先级队列

特点: 数据优先级越高,越先出来

JS代码实现:

class PriorityQueue extends Queue {
  constructor(element, priority) {
    super();
    this.element = element;
    this.priority = priority;
  }
  enqueue(element, priority) {
    const qe = new PriorityQueue(element, priority);
    let isAdd = false;
    if (this.item.length == 0) {
      this.item.push(qe);
      isAdd = true;
    } else {
      for (let i = 0; i < this.item.length; i++) {
        if (qe.priority < this.item[i].priority) {
          this.item.splice(i, 0, qe);
          isAdd = true;
          break;
        }
      }
      if (!isAdd) {
        this.item.push(qe);
      }
    }
  }
  toString() {
    let result = '';
    for (let i = 0; i < this.item.length; i++) {
      result += this.item[i].element + ' ';
    }
    return result;
  }
}

你可能感兴趣的:(Js数据结构之栈与队列)