这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
这篇文章主要介绍了 javascript 编程实现栈的方法, 简单说明了栈的概念、特点并结合实例形式分析了 javascript 栈的定义、入栈、出栈等操作相关实现技巧, 需要的朋友可以参考下
本文实例讲述了 javascript 编程实现栈的方法。分享给大家供大家参考,具体如下:
栈是限定仅在表尾进行插入或删除操作的线性表,栈是先进后出的。栈的表尾称为栈顶(top),而表头端称为栈底(bottom)。
和线性表类似,栈也有两种存储表示方法,顺序栈和链栈。
这里讲一下顺序栈,设置指针 top 指示栈顶元素在顺序栈中的位置。通常的做法就是以 top=0 表示空栈。base 为栈底指针,top 为栈顶指针。
如果 base 为 null,则表示栈结构不存在,如果 top=base 则表示空栈。每当插入一个新的元素,top+1,删除元素,top-1。因此,非空栈中 top 始终在栈顶元素的下一位置上。
如下图所示
JavaScript 中自带了数组的 push 和 pop 方法,其原理无非就是数组最后继续添加和删除数组最后一个元素。这里我们自己实现一遍栈的操作,代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>
- JS栈
- </title>
- </head>
- <body>
- <script type="text/javascript">
- function Stack(count) {
- var top = -1; //top头指针
- this.myArray = new Array();
- if (count != undefined) {
- this.count = count;
- this.myArray = new Array(this.count);
- } else {
- this.count = 0;
- }
- //入栈
- this.In = function(value) {
- if (top == this.count) {
- return false;
- } else {++top;
- this.myArray[top] = value;
- return true;
- }
- return false;
- }
- //出栈
- this.Out = function() {
- if (top == -1) {
- return false;
- } else {
- var removeValue = this.myArray[top];
- this.myArray[top] = null;
- top--;
- return removeValue;
- }
- }
- this.Clear = function() {
- this.top = -1;
- }
- //遍历栈
- this.tostring = function() {
- for (var i = 0; i < this.myArray.length; i++) {
- document.write(this.myArray[i] + '<br>');
- }
- }
- }
- Stack(3);
- In(1);
- In(2);
- In(3);
- tostring(); //1 2 3
- Out();
- Out();
- tostring(); //1 null null
- In(4);
- tostring(); //1 4 null
- </script>
- </body>
- </html>
首先需要定义头指针
- function Stack(count){
- var top=-1;//top头指针
- this.myArray=new Array();
- if(count!=undefined){
- this.count=count;
- this.myArray=new Array(this.count);
- }else{
- this.count=0;
- }
然后是入栈操作
- //入栈
- this.In=function(value){
- if(top==this.count){
- return false;
- }else{
- ++top;
- this.myArray[top]=value;
- return true;
- }
- return false;
- }
和出栈操作
- //出栈
- this.Out=function(){
- if(top==-1){
- return false;
- }else{
- var removeValue=this.myArray[top];
- this.myArray[top]=null;
- top--;
- return removeValue;
- }
- }
链栈的操作和链表类似,这里就不做详细介绍了。
希望本文所述对大家 JavaScript 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0628/334143.html