首页 > 代码库 > js:数据结构笔记2---列表

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() {   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-1) {    ++this.pos;  }}function currPos() {  return this.pos;}function moveTo(position) {  this.pos = position;}function getElement() {  return this.dataStore[this.pos];}

 

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