javascript数据结构[列表]

1.列表

//定义列表类构造函数
function List(){
    /**
    *抽象数据类型定义
    *listSize 列表的元素个数
    *pos 列表的当前位置
    *length() 返回列表中元素的个数
    *clear() 清空列表中所有的元素
    *toString() 返回列表的字符串形式
    *getElement() 返回当前位置的元素
    *insert() 在现有元素后插入新元素
    *append() 在列表的末尾添加新元素
    *remove() 从列表中删除元素
    *front() 将列表的当前位置移动到第一个元素
    *end() 将列表的当前位置移动到最后一个元素
    *prev() 将当前位置前移一位
    *next() 将当前位置后移一位
    *currPos() 返回列表的当前位置
    *moveTo() 将当前位置移动到指定位置
    **/
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = [];
    this.clear = clear;
    this.find = find;
    this.toString = toString;
    this.insert = insert;
    this.append = append;
    this.remove = remove;
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.length = length;
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.getElement = getElement;
    this.contains = contains;
}

//给列表添加元素
function appand(element){
  this.dataStore[this.listSize++] = element;
}
//从列表中查找一个元素
function find(element){
  for(var i = 0;  i < this.dataStore.length; i++ ){
     if(this.dataStore[i] === element){
         return i;
     }
  }
  return -1;
}    
  
//从列表中删除元素
function remove(element){
  var foundAt = this.find(element);
  if(foundAt > -1){
    this.dataStore.splice(foundAt,1);
    this.listSize--;
    return true;
  }
 return false;
}

//返回列表中的元素个数
function length(){
  return this.listSize;
}

//显示列表中的元素
function toString(){
  return this.dataStore;
}

//向列表中插入一个元素
function insert(element,after){
  var insertPos = this.find(after);
  if(insertPos > -1){
    this.dataStore.splice(insertPos,0,element);
    this.listSize++;
   return true;
  }
 return false;
}

//清空列表中的所有元素
function remove(){
  delete this.dataStore;
  this.dataStore = [];
  this.listSize = this.pos = 0;
}

//判断给定的值是否在列表中
function contains(element){
  for(var i = 0; i < this.dataStore.length; i++){
    if(this.dataStore[i] === element){
      return true;
    }
  }
 return false;
}
//移动到第一个元素
function front(){
  this.pos = 0;
}

//移动到最后一个元素
function end(){
  this.pos =  this.listSize - 1;
}

//往前移动一位
function prev(){
  if(this.pos > 0){
    this.pos--;
  }
}

//往后移动一位
function next(){
  if(this.pos < this.listSize - 1){
    this.pos++;
  }
}

//当前位置
function currPos(){
  return this.pos;
}

//移动到指定位置
function moveTo(position){
  this.pos = position;
}

//获得当前元素
function getElement(){
   return this.dataStore[this.pos]; 
}

你可能感兴趣的:(javascript数据结构[列表])