Created
November 18, 2019 17:13
-
-
Save Jagathishrex/5f6b9c9b3e3aa04ddd1ba0e4e2996f0e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stack { | |
constructor(){ | |
this.data = []; | |
this.top = 0; | |
} | |
push(element) { | |
this.data[this.top] = element; | |
this.top = this.top + 1; | |
} | |
length() { | |
return this.top; | |
} | |
peek() { | |
return this.data[this.top-1]; | |
} | |
isEmpty() { | |
return this.top === 0; | |
} | |
pop() { | |
if( this.isEmpty() === false ) { | |
this.top = this.top -1; | |
return this.data.pop(); // removes the last element | |
} | |
} | |
print() { | |
var top = this.top - 1; // because top points to index where new element to be inserted | |
while(top >= 0) { // print upto 0th index | |
console.log(this.data[top]); | |
top--; | |
} | |
} | |
reverse() { | |
this._reverse(this.top - 1 ); | |
} | |
_reverse(index) { | |
if(index != 0) { | |
this._reverse(index-1); | |
} | |
console.log(this.data[index]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment