JavaScript Stack Implementation

This example shows how to use a simple stack to sum array values.


function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}

function push(element) {
this.dataStore[this.top++] = element;
}

function pop() {
return this.dataStore[--this.top];
}

function peek() {
return this.dataStore[this.top-1];
}

function length() {
return this.top;
}

function clear() {
this.top = 0;
}

function sumArr(num) {
var st = new Stack();
var len = num.length;
var sum = 0;

for(var i = 0; i < len; i++) {
st.push(num[i]);
}
while(st.length() > 0) {
sum += st.pop();
}
return sum;
}
var arr = [1,2,3,4,5,6];
console.log(sumArr(arr));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s