• js:数据结构笔记2---列表


    列表:

    • 定义:一组有序的数据;
    function List() {
       this.listSize = 0;
       this.pos = 0;
       this.dataStore = [];
       this.find = find;
       .........................
    }
    • 方法:
      • append:添加数据

    function append(element) { this.dataStore[this.listSize++] = element; }

      • find:查找元素://indexOf
     function find(element) {
          for(var i=0; i < this.dataStore.length; ++i) {
           if(this.dataStore[i] === element) {
                return 1;  
          }
       }
        return -1;
    }
      • remove:删除元素;
     function  remove(element) {
       var foundAt = this.find(element);
       if(foundAt > -1) {
         this.dataStore.splice(foundAt,1);
         --this.listSize;
         return true;
       }
       return false;
    }
      • length:返回元素个数;
    function length() {
       return this.listSize;
    }
    
      • toString:显示元素;
    function toString() {
       return this.dataStore;
    }
      • insert:插入元素;
    function insert(elem,after) {
       var insertPos = this.find(elem);
       if(insertPos > -1) {
         this.dataStore.splice(insertPos+1,0,elem);  //
         ++this.listSize;
         return true;
      }
      return false;
    }
      • clear:清空所有元素;
    function clear() {
       delete this.dataStore;
       this.dataStore = [];
       this.listSize = this.pos = 0;
    }
      • contains:判断元素;
    function contains(elem) {
       for(var i = 0; i < this.dataStore.length; ++i) {
          if(this.dataStore[i] ===  elem) {
              return true;
         }
      }
         return false;
    }
      • 遍历:
    function front() {
      this.pos = 0;    //pos范围[0-listSize-1]
    }
    
    function end() {
      this.pos = this.listSize - 1;
    }
    
    function prev() {
      if(this.pos > 0) {
        --this.pos;
      }
    }
    
    function next() {
      if(this.pos < this.listSize) {
        ++this.pos;  //
      }
    }
    
    function currPos() {
      return this.pos;
    }
    
    function moveTo(position) {
      this.pos = position;
    }
    
    function getElement() {
      return this.dataStore[this.pos];
    }

    使用迭代器访问列表:迭代器只是用来在列表上随意移动,而不应该和任何为列表增加或删除的方法一起使用;

    demo

  • 相关阅读:
    PHP pcntl
    Linux 远程登录命令telnet
    git .gitignore不生效
    使用 GoLand 启动 运行 Go 项目
    Go语言: 万物皆异步
    MYSQL 单表一对多查询,将多条记录合并成一条记录
    详解PHP中instanceof关键字及instanceof关键字有什么作用
    all_user_func()详解
    python的反射
    python 的魔术方法
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/4021503.html
Copyright © 2020-2023  润新知