Programma JavaScript per implementare uno stack

In questo esempio, imparerai a scrivere un programma JavaScript che implementerà uno stack.

Per comprendere questo esempio, è necessario conoscere i seguenti argomenti di programmazione JavaScript:

  • JavaScript Array push ()
  • JavaScript Array pop ()
  • Metodi JavaScript e questa parola chiave

Lo stack è una struttura dati che segue il principio Last In First Out (LIFO) . All'elemento che viene aggiunto finalmente si accede per primo. È come impilare i tuoi libri uno sopra l'altro. Il libro che hai messo alla fine viene prima.

Esempio: stack dell'attrezzo

 // 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);

Produzione

 (1, 2, 4, 8) (1, 2, 4) 4 falso 3 ()

Nel programma precedente, la Stackclasse viene creata per implementare la struttura dati dello stack. I metodi della classe come add(), remove(), peek(), isEmpty(), size(), clear()sono implementati.

Uno stack di oggetti viene creato utilizzando un newoperatore e vari metodi sono accessibili tramite l'oggetto.

  • Qui, inizialmente this.items è un array vuoto.
  • Il push()metodo aggiunge un elemento a this.items.
  • Il pop()metodo rimuove l'ultimo elemento da this.items.
  • La lengthproprietà fornisce la lunghezza di this.items.

Articoli interessanti...