Bir Yığın Uygulamak için JavaScript Programı

Bu örnekte, bir yığın uygulayacak bir JavaScript programı yazmayı öğreneceksiniz.

Bu örneği anlamak için, aşağıdaki JavaScript programlama konuları hakkında bilgi sahibi olmalısınız:

  • JavaScript Dizisi itme ()
  • JavaScript Dizisi pop ()
  • JavaScript Yöntemleri ve bu Anahtar Kelime

Yığın, Last In First Out (LIFO) ilkesini izleyen bir veri yapısıdır . Son olarak eklenen elemana ilk önce erişilir. Bu, kitaplarınızı üst üste dizmek gibidir. Sonunda koyduğunuz kitap önce gelir.

Örnek: Yığını Uygulama

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

Çıktı

 (1, 2, 4, 8) (1, 2, 4) 4 yanlış 3 ()

Yukarıdaki programda, Stacksınıf, yığın veri yapısını uygulamak için oluşturulur. Sınıf yöntemleri gibi add(), remove(), peek(), isEmpty(), size(), clear()uygulanmaktadır.

Bir newoperatör kullanılarak bir nesne yığını oluşturulur ve nesne üzerinden çeşitli yöntemlere erişilir.

  • Burada, başlangıçta this.items boş bir dizidir.
  • push()Yöntem this.items bir eleman eklemektedir.
  • pop()Yöntem this.items geçen öğeyi kaldırır.
  • lengthMülkiyet this.items uzunluğunu verir.

Ilginç makaleler...