Рубрики
Без рубрики

Как реализовать стек в ванильном JavaScript и ES6

PraShant Yadav Как реализовать стек в стеке в стеке Vanilla JavaScript и ES6A – это заказанная коллекция элементов, которые следуют за последним в принципе «LIFO). Дополнение и удаление предметов происходят в одном итоге, то есть на вершине. Новейшие элементы

Автор оригинала: FreeCodeCamp Community Member.

Прашант Ядав

А стек это заказанная коллекция предметов, которые следуют за Последнее в первом месте (Lifo) принцип. Дополнение и удаление предметов происходят в одном итоге, то есть на вершине. Новейшие элементы на вершине, а самые старые элементы находятся внизу.

У нас много примеров Стеки вокруг нас как куча книг, стопку лотков или блюд и т. Д.

А Стек Используется компиляторами на языках программирования по памяти компьютера для хранения переменных и вызовов функций, а также в текстовых редакторах для выполнения операций Undo & Redo.

Список операций, выполняемых на стеке

  • push () : Добавляет один или несколько элементов на верхнюю часть стека.
  • POP () : Удаляет и возвращает верхний элемент стека.
  • PEEK () : Возвращает верхний элемент стека.
  • ushumpy () : Возвращает Правда Если стек пуст, Ложь иначе.
  • Очистить () : Удаляет все предметы из стека.
  • Размер () : Возвращает длину стека.

Создание стека

Классический подход

Мы собираемся реализовать стек Как то, как он реализован на других языках, кроме JavaScript.

Мы будем использовать массив и Дополнительная переменная отслеживать предметы.

function Stack(){   var items = [];   var top = 0;   //other methods go here }

Нажмите предмет в стеке

//Push an item in the Stackthis.push = function(element){  items[top++] = element } //top++, first performs the operation then increment's the value

Поп-предмет из стека

//Pop an item from the Stackthis.pop = function(){  return items[--top]; } //--top, first decrements the value then performs the operation

Главный предмет из стека

//peek an item in the Stackthis.peek = function(){   return items[top - 1]; }

Проверьте, пуст стека

//Is stack emptythis.isEmpty = function(){   return top === 0; }

Очистить стек

//clear the stackthis.clear= function(){   top = 0; }

Размер стека

//Size of the Stackthis.size = function(){   return top; }

Полная реализация стека

function Stack(){   var items = [];   var top = 0;   //other methods go here 
  //Push an item in the Stack   this.push = function(element){      items[top++] = element   } //top++, first performs the operation then increment's the value 
  //Pop an item from the Stack   this.pop = function(){      return items[--top];   } //--top, first decrements the value then performs the operation 
  //Peek top item of the Stack   this.peek = function(){      return items[top - 1];   } 
  //Is Stack empty   this.isEmpty = function(){     return top === 0;   } 
  //Clear the Stack   this.clear = function(){     top = 0;   } 
  //Size of the Stack   this.size = function(){      return top;   }
}

Пример

Теперь мы создадим новый экземпляр того, что мы реализовали и проверили, правильно ли он работает.

var stack = new Stack(); //creating new instance of Stack stack.push(1); stack.push(2); stack.push(3); console.log(stack.peek()); console.log(stack.isEmpty()); console.log(stack.size()); console.log(stack.pop()); console.log(stack.size()); stack.clear(); console.log(stack.isEmpty()); 
Output: 3 false 3 3 2 true

Реализация стека с JavaScript

Мы собираемся реализовать стек с JavaScript массив который имеет встроенные методы, такие как толчок и поп.

function Stack(){   var items = [];   //other methods go here }

Нажмите предмет в стеке

//push an item in the Stackthis.push = function(element){   items.push(element); }

Поп-предмет из стека

//Pop an item from the Stackthis.pop = function(){   return items.pop(); }

Главный предмет из стека

//Peek top item of the Stackthis.peek = function(){   return items[items.length - 1]; }

Проверьте, пуст стека

//Is Stack emptythis.isEmpty = function(){    return items.length === 0; }

Очистить стек

//Clear the Stackthis.clear = function(){   items.length = 0; }

Размер стека

//Size of the Stackthis.size = function(){   return items.length; }

Полная реализация стека

function Stack(){   var items = [];   //other methods go here 
  //Push a item in the Stack   this.push = function(element){      items.push(element);   } 
  //Pop a item from the Stack   this.pop = function(){      return items.pop();   } 
  //Peek top item of the Stack   this.peek = function(){      return items[items.length - 1];   }
  //Is Stack empty   this.isEmpty = function(){      return items.length === 0;   } 
  //Clear the Stack   this.clear = function(){      items.length = 0;   } 
  //Size of the Stack   this.size = function(){      return items.length;   } 
}

Создание свойств и методов частных с закрытием и IIFE (немедленно вызывало функцию выражения).

var Stack = (function () {   return function Stack(){     var items = [];    //other methods go here 
    //Push an item in the Stack     this.push = function(element){        items.push(element);     } 
    //Pop an item from the Stack     this.pop = function(){        return items.pop();     } 
    //Peek top item from the Stack     this.peek = function(){        return items[items.length - 1];     } 
    //Is Stack empty     this.isEmpty = function(){         return items.length === 0;     } 
    //Clear the Stack     this.clear = function(){        items.length = 0;     }         //Size of the Stack this.size = function(){        return items.length;     }   }})();

Стек с использованием ES6.

class Stack{  constructor(){    this.items = [];  }     //other methods go here   //Push an item in the Stack   push = function(element){     this.items.push(element);   }
//Pop an item from the Stack   pop = function(){     return this.items.pop();   }        //Peek top item from the Stack   peek = function(){     return this.items[this.items.length - 1];   }
//Is Stack empty   isEmpty = function(){     return this.items.length === 0;   }
//Clear the Stack   clear = function(){      this.items.length = 0;   }        //Size of the Stack   size = function(){     return this.items.length;   }}

Стек с использованием Shavmap ES6.

const items = new WeakMap();class Stack{  constructor(){    items.set(this, []);  }     //other methods go here   //Push an item in the Stack   push = function(element){     let temp = items.get(this);     temp.push(element);   }
//Pop an item from the Stack   pop = function(){     let temp = items.get(this);     return temp.pop();   }        //Peek top item from the Stack   peek = function(){     let temp = items.get(this);     return temp[temp.length - 1];   }
//Is Stack empty   isEmpty = function(){     let temp = items.get(this);     return temp.length === 0;   }
//Clear the Stack   clear = function(){      let temp = items.get(this);      temp.length = 0;   }        //Size of the Stack   size = function(){     let temp = items.get(this);     return temp.length;   }}

Создание свойств и методов частных с закрытием и IIFE (немедленно вызываемая функциональная экспрессия) для стека с использованием слабого управления ES6.

let Stack = (() => {  const items = new WeakMap();  return class Stack{    constructor(){      items.set(this, []);    }
//other methods go here     //Push an item in the Stack     push = function(element){       let temp = items.get(this);       temp.push(element);     }
//Pop an item from the Stack     pop = function(){       let temp = items.get(this);       return temp.pop();     }
//Peek top item from the Stack     peek = function(){       let temp = items.get(this);       return temp[temp.length - 1];     }
//Is Stack empty     isEmpty = function(){       let temp = items.get(this);       return temp.length === 0;     }
//Clear the Stack     clear = function(){        let temp = items.get(this);        temp.length = 0;     }
//Size of the Stack     size = function(){       let temp = items.get(this);       return temp.length;     }  }})();

Сложность времени

# В среднем

Доступ: θ (n)

Поиск: θ (n)

Вставить: θ (1)

Удалить: θ (1)

# Наихудший

Доступ: O (n)

Поиск по)

Вставить: O (1)

Удалить: O (1)

Космическая сложность

# Худший : НА)

Есть много проблем, где стек может быть идеальной структурой данных, необходимой для решения.

Если вам понравилась эта статья, пожалуйста, дайте ей? И поделитесь этим! Если у вас есть какие-либо вопросы, связанные с этим, не стесняйтесь спрашивать меня.

Для большего количества таких и алгоритмических решений в JavaScript следуйте за мной на Twitter Отказ Я пишу о ES6 , Реагировать, nodejs, Структуры данных и Алгоритмы на Nearnersbucket.com Отказ

Оригинал: “https://www.freecodecamp.org/news/stack-5404d9735f88/”