“Stapelimplementierung in JavaScript mit Array” Code-Antworten

Stapelimplementierung in JavaScript mit Array

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

Stapel in 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

Ähnliche Antworten wie “Stapelimplementierung in JavaScript mit Array”

Fragen ähnlich wie “Stapelimplementierung in JavaScript mit Array”

Weitere verwandte Antworten zu “Stapelimplementierung in JavaScript mit Array” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen