数据结构:JavaScript实现列表

列表是一组有序的数据,每个列表中的数据项称为元素

在javascript中,列表中的元素可以是任意数据类型,列表中可以保存多少元素并没有实现限定,实际使用时元素的数量受到程序内存的限制

代码以及解释如下

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.currPos = currPos;
	this.moveTo = moveTo;
	this.getElement = getElement;
	this.contains = contains;

	
}


//给列表添加一个新元素
function append(element){
	//新元素就位后,变量listSize加一,即列表长度加一
	this.dataStore[this.listSize++] = element;
}
//从列表中删除元素,想要删除某个元素,首先要从列表中找到她,这里我们写一个find函数来做这件事情
function remove(element){
	var fountAt = this.find(element);
	if(fountAt > -1){
		this.dataStore.splice(fountAt, 1);
		--this.listSize;
		return true;
	}
	return false;
}
//remove方法借助的find方法
function find(element){
	for (var i = 0; i < this.dataStore.length; i++) {
		if(this.dataStore[i] == element){
			return i;
		}
	}
	return -1;
}
//列表中元素的个数
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 + 1, 0, element);
		++this.listSize;
		return true;
	}
	return false;
}
//清空列表中的所有元素
function clear(){
	delete this.dataStore;
	this.dataStore = [];
	this.listSize = 0;
	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];
}

测试一下

//测试一下!
var names = new List();
names.append("miaomiao");
names.append("jingjing");
names.append("asong");
names.append("shisisong");
names.append("qingsong");
console.log(names.toString());
names.remove("asong");
console.log(names.toString());
names.insert("duansong", "jingjing");
console.log(names.toString());
var flag = names.contains("shisisong");
console.log(flag);
names.front();
names.next();
names.next();
names.prev();
console.log(names.getElement());
names.clear();
console.log(names.toString());

输出结果如下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值