Javascipt 数据结构 之 Stack

来源:互联网 发布:simsun.ttc linux 编辑:程序博客网 时间:2024/05/17 04:48

Stack 是一种特殊的数据类型或集合,Stack 实现了先进先出的操作( LIFO -- Last In First Out )

主要操作: 成员的增加 称为push, 成员的删除称为 pop


/** * Created by hatmore on 13-12-24. */function Stack() {    var top = null;    var count = 0;    //返回Stack 里的成员个数    this.GetCount = function(){        return count;    }    //方法    //压入成员    this.Push = function(data) {        var node = {            data:data,            next:null        };        node.next = top;        top = node;    };    //获取Stack顶部的数据,如果 Stack是空的返回null    this.Peek = function(){        if(top === null) {            return null;        } else {            return top.data;        }    }    this.Pop = function() {        //如何没有数据返回null        if (top === null) {            return null;        } else {            //被弹出的成员,分配给一个临时变量            var out = top;            //top.next, 成为顶部成员            top = top.next;            //Stack 中 剩下的成员            if (count >0) {                count --;            }            //返回弹出的数据            return out.data;        }    }}


0 0
原创粉丝点击