“Implémentation de pile dans JavaScript à l'aide du tableau” Réponses codées

Implémentation de pile dans JavaScript à l'aide du tableau

class Stack{
    constructor(){
        this.array = [];
        this.count = 0;
    }

    isEmpty(){
        return this.count == 0;
    }

    size(){
        return this.count;
    }

    peekTop() {
        if(this.count == 0){
            return "Stack is Empty";
        }
        return this.array[this.count-1];
    }

    peek(pos){
        var top =this.count-1;
        if(top-pos+1<0)
            return "invalid index";
        else
            return this.array[top-pos+1];
    }

    push(data){
        this.count++;
        this.array.push(data);
    }

    pop(){
        if(this.array.length == 0)
            return "Stack is Underflow";
        this.count--;
        return this.array.pop();
    }

    print(){
        if(this.count == 0){
            return "Unable to Print,Stack is Empty :-(";
        }
        var str = "";
        for (var i = this.array.length-1; i >= 0; i--)
            str += this.array[i] + " ";
        return str;
    }
}

const arrStack = new Stack();
arrStack.push("10");
arrStack.push("20");
arrStack.push("30");
arrStack.push("40");
console.log("Peek Top element is ",arrStack.peekTop());
arrStack.push("50");
console.log("Poped element in stack ",arrStack.pop());
console.log("Peeked element at position 2",arrStack.peek(2));
console.log("element in stack\n",arrStack.print());
console.log("is Stack empty? ",arrStack.isEmpty());
console.log("Size of stack is ",arrStack.size());

/**
 * Time Complexity -> O(1) (all opeartion take constant time)
 * Space Complexity -> O(1)
 */
Aayush

empiler en javascript

class Stack{
   constructor() 
    { 
        this.items = []; 
    } 
   
    push(element) 
   { 
    // push element into the items 
    this.items.push(element); 
    }
  
    pop() 
    { 
    if (this.items.length == 0) 
        return "Underflow"; 
    return this.items.pop(); 
    } 
  
    peek() 
	{ 
    	return this.items[this.items.length - 1]; 
	} 
  
    printStack() 
    { 
    	var str = ""; 
    	for (var i = 0; i < this.items.length; i++) 
        	str += this.items[i] + " "; 
    	return str; 
    } 

}
Mak009

Réponses similaires à “Implémentation de pile dans JavaScript à l'aide du tableau”

Questions similaires à “Implémentation de pile dans JavaScript à l'aide du tableau”

Plus de réponses similaires à “Implémentation de pile dans JavaScript à l'aide du tableau” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code