この例では、スタックを実装するJavaScriptプログラムの作成方法を学習します。
スタックは次のデータ構造です 後入れ先出し(LIFO) 原理。 最後に追加された要素が最初にアクセスされます。 これは、本を積み重ねるようなものです。 ついに置いた本が先に来る。
例:スタックの実装
// 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);
出力
[1, 2, 4, 8] [1, 2, 4] 4 false 3 []
上記のプログラムでは、 Stack
クラスは、スタックデータ構造を実装するために作成されます。 次のようなクラスメソッド add()
、 remove()
、 peek()
、 isEmpty()
、 size()
、 clear()
実装されています。
オブジェクトスタックは、 new
演算子とさまざまなメソッドは、オブジェクトを介してアクセスされます。
- ここで、最初は this.items 空の配列です。
- ザ・
push()
メソッドは要素をに追加します this.items。 - ザ・
pop()
メソッドは最後の要素をから削除します this.items。 - ザ・
length
プロパティはの長さを与えます this.items。
Hope this helps!