使用js完成链表

128 阅读1分钟

// 1.单向链表 在js中有序的数据类型、数据结构:数组 // 线性的数据结构 next Data // 2.双向链表:next Data pre // 3.单向循环链表 // 4.双向循环链表 // 5.环形链表 // //

class Node{
        constructor(element){
	this.element = element;
	this.next = null;
            }
}

class LinkedList{
        constructor(){
                this.size = 0;//当前的长度
                this.head = null;//头指针
        }
append(element){
	// 追加元素
	// 如果链表为空就追加到最前面,否则追加到最后一位
	let node = new Node(element);
		if(this.head === null)
			// 或者 size ===0
			{
				this.head = node
			}else{
				let current = this.getNode(this.size -1);
				current.next = node;
			}
			this.size ++
	}

appendAt(position,element){
	// 在指定位置插入元素
	if(position<0 || position>this.size){
		throw new Error('数据错误')
	}
	let node = new Node(element);
	if(position === 0){
		node.next = this.head;
		this.head = node;
	}else{
		let pre = this.getNode(position - 1);
		// 拿到前一个节点
		node.next = pre.next;
		pre.next = node;
	}
	this.size ++
}
removeAt(position){
	// 删除指定项元素
	// 边界判断
	if(position<0 || position>=this.size){
		throw new Error('数据错误')
	}
	let current = this.head;
	if(position === 0){
		// 移除头节点
	this.head = current.next;
	}else{
		// 删除中间
		let pre = this.getNode(position - 1);//前一个节点
		current = pre.next;
		pre.next = current.next;
	}
	this.size --
}
indexOf(element){
	// 查找指定元素的索引
	let current = this.head;
	for(var i = 0;i<this.size;i++){
		if(current.element === element){
			return i
		}
		current = current.next
	}
	return -1
}
getNode(index){
	// 根据索引获取到最后一个元素
	// 处理一下边界性问题
	if(index<0 || index>= this.size){
		throw new Error('数据错误')
	}
	let current = this.head;
	for(var i =0;i<index;i++){
		current = current.next
	}
	return current
        }
}

let ll = new LinkedList();
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
// ll.appendAt(2,3)
// ll.appendAt(3,4)
// ll.appendAt(3,2)
// ll.appendAt(4,5)
// ll.removeAt(0)
console.log(ll.indexOf(1))
console.dir(ll,{
        depth:100
})