mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-07 02:05:08 +08:00
Merge pull request #45 from christianbender/changed_stack
wrote prototype notation
This commit is contained in:
@ -7,21 +7,22 @@
|
|||||||
|
|
||||||
// Functions: push, pop, peek, view, length
|
// Functions: push, pop, peek, view, length
|
||||||
|
|
||||||
//Creates a stack
|
//Creates a stack constructor
|
||||||
var Stack = function () {
|
var Stack = function () {
|
||||||
//The top of the Stack
|
//The top of the Stack
|
||||||
this.top=0;
|
this.top=0;
|
||||||
//The array representation of the stack
|
//The array representation of the stack
|
||||||
this.stack = {};
|
this.stack = new Array();
|
||||||
|
}
|
||||||
|
|
||||||
//Adds a value onto the end of the stack
|
//Adds a value onto the end of the stack
|
||||||
this.push=function(value) {
|
Stack.prototype.push=function(value) {
|
||||||
this.stack[this.top]=value;
|
this.stack[this.top]=value;
|
||||||
this.top++;
|
this.top++;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Removes and returns the value at the end of the stack
|
//Removes and returns the value at the end of the stack
|
||||||
this.pop = function(){
|
Stack.prototype.pop = function(){
|
||||||
if(this.top === 0){
|
if(this.top === 0){
|
||||||
return "Stack is Empty";
|
return "Stack is Empty";
|
||||||
}
|
}
|
||||||
@ -33,21 +34,20 @@ var Stack = function () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Returns the size of the stack
|
//Returns the size of the stack
|
||||||
this.size = function(){
|
Stack.prototype.size = function(){
|
||||||
return this.top;
|
return this.top;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Returns the value at the end of the stack
|
//Returns the value at the end of the stack
|
||||||
this.peek = function(){
|
Stack.prototype.peek = function(){
|
||||||
return this.stack[this.top-1];
|
return this.stack[this.top-1];
|
||||||
}
|
}
|
||||||
|
|
||||||
//To see all the elements in the stack
|
//To see all the elements in the stack
|
||||||
this.view= function(){
|
Stack.prototype.view= function(){
|
||||||
for(var i=0;i<this.top;i++)
|
for(var i=0;i<this.top;i++)
|
||||||
console.log(this.stack[i]);
|
console.log(this.stack[i]);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
//Implementation
|
//Implementation
|
||||||
var myStack = new Stack();
|
var myStack = new Stack();
|
||||||
|
Reference in New Issue
Block a user