js实现栈结构

146 阅读1分钟

基本概念

  • 先进后出
  • 只在一端进行入栈和出栈操作

基于数组实现栈

       class Stack {
           constructor() {
               this.items = [];
           }
           push(element) {
             this.items.push(element)
           }
           pop() {
               return this.items.pop();
           }
           peek() {
               return this.items[this.items.length - 1]
           }
           size() {
               return this.items.length;
           }
           isEmpty() {
               return this.size() === 0;
           }
           clear() {
               this.items = [];
           }
       }

基于对象实现栈

       class Stack {
           constructor() {
               this.count = 0; // 记录栈的大小
               this.items = {}; // 存储栈元素
           }
           push(element) {
             this.items[this.count] = element;
             this.count++;
           }
           pop() {
               if (this.isEmpty()) {
                return undefined
               }
               this.count--;
               const item = this.items[this.count];
               delete this.items[this.count]
               return item;
           }
           peek() {
            if (this.isEmpty()) {
                return undefined
               }
               return this.items[this.count - 1]
           }
           size() {
               return this.count;
           }
           isEmpty() {
               return this.count === 0
           }
           clear() {
               this.count = 0;
               this.items = {};
           }
           toString() {
               if (this.isEmpty()) {
                 return ''
               }
               let str = this.items[0];
               for (let i = 1; i < this.count; i++) {
                 str = `${str},${this.item[i]}`;
               }
               return str;
           }          
       }