码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 数据结构和算法读书笔记 > 第三章 列表

时间:2015-01-15 15:30:01      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

1. 结构分析

列表首先要有以下几个属性:

  listSize 长度

  pos 当前位置

  dataStore 数据

我们要通过以下方法对上面三个属性进行操作:

  length() 获取长度 | getPos() 获取当前位置   |   toString() 打印list内容

  add(ele) 顺序添加元素   |   insert(newEle, afterEle) 在某元素后插入元素  |  remove(ele) 删除某元素

  clear() 清空列表  |  find(ele) 查询元素位置  |  get(index) 根据位置获取元素  |  contain(ele) 是否包含某元素

  prev() 下标前移一位  |  next() 下标后移一位   |   front() 定位到头部  |   end() 定位到尾部

2. 实现:

function List(){
    this.listSize = 0;
    this.dataStore = [];
    this.pos = 0;

    this.length = function(){ 
        return this.listSize;
    };
    this.getPos = function(){
        return this.pos;
    };
    this.prev = function(){
        this.pos--;
    };
    this.next = function(){
        this.pos++;
    };
    this.front = function(){
        this.pos = 0;
        return 0;
    };
    this.end = function(){
        this.pos = this.listSize;
        return this.listSize;
    };
    this.find = function(ele){
        for(var i=0; i<this.listSize; i++){
            if(this.dataStore[i] === ele){
                return i;
            }
        }
        return -1;
    };
    this.add= function(ele){
        this.dataStore[this.listSize++] = ele;
    };
    this.insert = function(ele, afterEle){
        var index = this.find(afterEle);
        if(index > -1){
            this.dataStore.splice(index, 0, ele);
            this.listSize++;
            return true;
        }else{
            return false;
        }
    };
    this.remove = function(ele){
        var index = this.find(ele);
        if(index > -1){
            this.dataStore.splice(index, 1);
            this.listSize--;
            return true;
        }
        return false;
    };
    this.clear = function(){
        delete this.dataStore;
        this.dataStore = [];
        this.listSize = this.pos = 0;
    };
    this.contains = function(ele){
        if(this.find(ele) > -1){
            return true;
        }else{
            return false;
        }
    };
    this.get = function(index){
        return this.dataStore[index];
    };
    this.toString = function(){
        return this.dataStore.toString();
    };
}

3. 应用:

var users = [‘Jenny‘, ‘Penny‘, ‘Tenny‘, ‘Anny‘, ‘Lily‘];
var list = new List();
for (var i = 0; i <users.length - 1; i++) {
    list.add(users[i]);
}
for(list.front(); list.getPos()<list.length(); list.next()){
    console.info(list.getPos() + ":" + list.get(list.curPos()));
}

 

  

javascript 数据结构和算法读书笔记 > 第三章 列表

标签:

原文地址:http://www.cnblogs.com/goupb/p/4226319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!