数据结构与算法-列表

在日常生活中,人们经常使用列表:待办事项列表、购物清单、十佳榜单、最后十名榜单 等。计算机程序也在使用列表,尤其是列表中保存的元素不是太多时。当不需要在一个很 长的序列中查找元素,或者对其进行排序时,列表显得尤为有用。反之,如果数据结构非 常复杂,列表的作用就没有那么大了。

列表的实现类:

function List(){
	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.curPos = curPos;
	this.moveTo = moveTo;
	this.getElement = getElement;
	this.contains = contains;
}
function append(element){
	this.dataStore[this.listSize++] = element;
}
function find(element){
	if((i=this.dataStore.indexOf(element))>=0){
		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 toString(){
	return this.dataStore.join(",");
}
function clear(){
	delete this.dataStore;
	this.dataStore = [];
	this.listSize = this.pos = 0;
}
function insert(element,after){
	var foundAt = this.find(after);
	if(foundAt>-1){
		this.dataStore.splice(foundAt+1,0,element);
		this.listSize++;
		return true;
	}
	return false;
}
function front(){
	this.pos = 0;
}
function end(){
	this.pos = this.listSize.length-1;
}
function prev(){
	if(this.pos>0){
		this.pos--;
	}
}
function next(){
	if(this.pos<(this.listSize.length-1)){
		this.pos++;
	}
}
function length(){
	return this.listSize.length;
}
function curPos(){
	return this.pos;
}
function moveTo(i){
	this.pos = i;
}
function getElement(){
	return this.listSize[this.pos];
}
function contains(ele){
	return this.listSize.indexOf(ele);
}

  • 支付宝二维码 支付宝
  • 微信二维码 微信

本文地址: /js-list.html

版权声明: 本文为原创文章,版权归 逐梦个人博客 所有,欢迎分享本文,转载请保留出处!

相关文章