Program JavaScript do implementacji stosu

W tym przykładzie nauczysz się pisać program JavaScript, który będzie implementował stos.

Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania JavaScript:

  • JavaScript Array push ()
  • JavaScript Array pop ()
  • Metody JavaScript i to słowo kluczowe

Stos to struktura danych zgodna z zasadą Last In First Out (LIFO) . Element, który został dodany jako ostatni, jest otwierany jako pierwszy. To jak układanie książek jedna na drugiej. Książka, którą w końcu włożyłeś, jest na pierwszym miejscu.

Przykład: implementacja stosu

 // program to implement stack data structure class Stack ( constructor() ( this.items = (); ) // add element to the stack add(element) ( return this.items.push(element); ) // remove element from the stack remove() ( if(this.items.length> 0) ( return this.items.pop(); ) ) // view the last element peek() ( return this.items(this.items.length - 1); ) // check if the stack is empty isEmpty()( return this.items.length == 0; ) // the size of the stack size()( return this.items.length; ) // empty the stack clear()( this.items = (); ) ) let stack = new Stack(); stack.add(1); stack.add(2); stack.add(4); stack.add(8); console.log(stack.items); stack.remove(); console.log(stack.items); console.log(stack.peek()); console.log(stack.isEmpty()); console.log(stack.size()); stack.clear(); console.log(stack.items);

Wynik

 (1, 2, 4, 8) (1, 2, 4) 4 fałsz 3 ()

W powyższym programie Stackklasa jest tworzona w celu implementacji struktury danych stosu. Metody klasy jak add(), remove(), peek(), isEmpty(), size(), clear()są realizowane.

Stos obiektów jest tworzony za pomocą newoperatora, a poprzez obiekt uzyskuje się dostęp do różnych metod.

  • Tutaj początkowo this.items jest pustą tablicą.
  • push()Metoda dodaje element do this.items.
  • pop()Metoda usuwa ostatni element z this.items.
  • lengthNieruchomość daje długość this.items.

Interesujące artykuły...