javascript 堆栈与列队

来源:互联网 发布:js 二维数组定义 编辑:程序博客网 时间:2024/06/09 04:27

javascript数组是一个逆天的存在,到了ecma262v5,它已经是堆栈,列队及迭代器的合体。有时候我们不需要这么强大的东西,这只要考虑到for循环太麻烦了,我们只需要非常简单的遍历,于是想用普通对象模拟一个就是。

首先是堆栈,先进后出


    function Stack(){   }              Stack.prototype = {                  add: function(el, pt){                      this._first =  pt = {//_first是不断变的                          _next:this._first,                          el: el                      }                      if (pt._next) {                          pt._next._prev = pt;                      }                      return this;                  }              }              var s = new Stack;              s.add("1").add("2").add("3")                           var pt = s._first;              while (pt) {                  console.log(pt.el)                  pt = pt._next;              }
接着是列队,先进先出:

 function Queue(){   }              Queue.prototype = {                  add: function(el){                      if( this._last ){                           this._last =  this._last._next = {//_last是不断变的                              el: el,                              _next: null//设置_last属性表示最后一个元素,并且让新增元素成为它的一个属性值                          }                      }else{                          this._last = this._first = {//我们要设置一个_first属性表示第一个元素                              el: el,                              _next: null                          }                      }                      return this;                  }              }              var q = new Queue              q.add("1").add("2").add("3")              var pt = q._first;              while (pt) {                  console.log(pt.el)                  pt = pt._next;              }


由于这两种结构的每个结点都是对象,因此它可以一直循环下去,直接_next为null。这样就避免[1,0,null,2]这样的集合遇假值中断的麻烦。

本文转载自 http://www.cnblogs.com/rubylouvre/archive/2012/11/23/2785051.html

0 0