javascript使用数组模拟栈

<!DOCTYPE>

<html>

 <head>

  <title> javascript使用数组模拟栈 </title>


  <meta charset="utf-8"/>


  <script type="text/javascript">


function MyStack(){

this.stackTop = -1;// 栈的指针

this.stackSize = 5;// 栈的容量

this.stack = new Array();


// 入栈操作

this.push = function(val){

if(this.stackTop == this.stackSize-1){

alert("栈已经满了");

}

this.stackTop++;

this.stack[this.stackTop] = val;

}

// 出栈操作

this.pop = function(){

if(this.stackTop == -1){

alert("栈内没有数据");

}

var stackTopVal = this.stack[this.stackTop];

this.stackTop--;

return stackTopVal;

}


// 显示栈内的数据

this.show = function(){

if(this.stackTop == -1){

alert("栈内没有数据");

}

for(var i = this.stackTop; i>-1; i--){

alert(this.stack[i]);

}

}

}


var stack = new MyStack();

stack.push("西瓜");

stack.push("橘子");

stack.show();

var valu = stack.pop();

alert("出栈的是:"+valu);

  </script>

 </head>


 <body>

 </body>

</html>


你可能感兴趣的:(javascript使用数组模拟栈)