javaScript数据结构基础之单链表
单链表的定义
单链表是一种链式存取的数据结构。每一个节点用元素的值➕后继元素组成。
代码实现
step1 首先将每一个节点的结构先表明
-
- 需要一个value值
-
- 还需要next来表示指向
class Node {
construtor(value){
//value 用来存放当前节点的值
this.value = value;
// next 用来指向下一个节点
this.next = null;
}
}
step2 确定链表的数据结构
- 每一个链表都需要有一个头部,用来存储第一个节点的信息
- 需要一个用来表示链表长度的变量,类似数组的length属性
- 需要一个用来判断节点是否相同的方法
class NodeList {
constructor(equalsFn = (a,b)=>{ return a === b}){
this.head = null;
this.count = 0;
this.equalsFn = equalsFn
}
}
step3 确定我们需要的方法
push 一个向尾部插入节点的方法
- 思路:
- 参考数组的push方法,我们需要提供的仅是一个值,在方法内部,会自己实现相关节点的链接操作
- 存在两种情况。1. 链表为空 2.链表不为空
function push(value) {
let node = new Node(value); // 创建一个上文描述的Node类型的节点
let current;
// 链表为空的时候,直接让链表的头为当前节点
if(this.count === 0) {
this.head = node;
}else {
// 如果链表不为空,则需要找到到最后的节点。而在链表中,节点接的联系是通过
//next实现的,所以只要找到node.next = null 的节点。
current = this.head;
while(current.next != null){
current = current.next
}
current.next = node;
}
this.count++;
return node;
}
removeAt一个根据指定位置删除元素的方法
- 思路:
- 1.检测输入的位置是否合法
- 2.如果想要删除当前位置的元素,肯定需要找到前一个元素,并且让前一个元素的next指向后一个元素。这样当前元素的链接关系便被我们打断
function removeAt (index) {
if(index >=0 && index <= this.count){
let current = this.head;
// 如果删除的是头部
if(index===0) {
this.head = current.next
}else {
// index > 0 的情况下,第一个肯定是头部,然后根据index变大,我们需要通过next寻找前一个节点(previous),当前节点(current)
let previous;
for(let i = 0; i < index; i++) {
previous = current;
current = current.next
}
previous.next = current.next
}
this.count--;
return current.value;
}
return undefined;
}
在removeAt方法中,我们花费了大量时间用来寻找指定位置的节点,考虑到此操作在链表中会经常用到,所以我们需要抽离出来一个 getElementAt 根据指定位置查找节点的方法
function getElementAt(index) {
if(index >= 0 && index <= this.count ) {
let current = this.head;
for(let i = 0; i<index ; i++) {
current = current.next
}
return current
}
return undefined
}