封裝優先順序佇列

m0_46679978發表於2020-11-29
 function PriorityStack() {
        this.items = [];
        function Priority(element, priority) {
          this.element = element;
          this.priority = priority;
        }
        PriorityStack.prototype.enquene = function (element, priority) {
          let member = new Priority(element, priority);
          if (this.items.length === 0) {
            this.items.push(member);
            return;
          }
          for (let i = 0; i < this.items.length; i++) {
            if (member.priority <= this.items[i].priority) {
              this.items.splice(i, 0, member);
              return;
            }
          }
          this.items.push(member);
        };
      }

      PriorityStack.prototype.dequene = function () {
        this.items.shift();
      };
      PriorityStack.prototype.size = function () {
        return this.items.length;
      };
      PriorityStack.prototype.isEmpty = function () {
        return this.items.length === 0;
      };
      PriorityStack.prototype.toString = function () {
        let str = "";
        for (let i = 0; i < this.items.length; i++) {
          str += this.items[i] + " ";
        }
        return str;
      };

相關文章