js单链表的实现

js实现简单的单链表 (初次接触,小白)

/* 定义一个节点类 */
class Node {
  constructor(element) {
    //元素本身
    this.element = element
    //指向位置
    this.next = null
  }
}

/* 定义列表 */
class MyList {
  constructor() {
    //列表的长度
    this.size = 0
    // 列表的头指针指向
    this.head = null
  }
  //向列表中添加元素
  append(element) {
    // 列表长度为0, 默认添加到头部
    if(this.head === null){
      this.head = new Node(element)
    }else{
      //获取列表的最后一个元素
      let lastElement = this.getNode(this.size -1)
      //最后一个元素的next 指向当前的元素
      lastElement.next = new Node(element)
    }
    //列表的长度自增
    this.size ++
  }
  /* 根据位置 索引 删除指定的元素 */
  remove(postion) {
    //position 越界判断
    if(postion < 0 || this.postion > this.size) {
      throw Error('out of position')
    }

    if(postion === 0) {
      // 删除列表的第一个元素
     this.head = this.head.next
    } else {
      //获取当前索引的上一个元素
      const preNode = this.getNode(postion - 1)
      //获取当前索引的元素
      const curNode = this.getNode(postion)
      //上一个节点的 next 指向 当前节点的 next
      preNode.next = curNode.next
    }
    // 列表的长度减一
    this.size --
  }
  /* 向列表中插入元素 position 插入的位置   element插入的元素 */
  insert(postion, element) {
    // 插入索引越界处理
    if(postion < 0 || this.postion > this.size) {
      throw Error('out of position')
    }
    // new 出来当前的节点
    let current = new Node(element)
    //position === 0 向列表的头部插入
    if(postion === 0) {
      current.next = this.head
      this.head = current
    }else {
      //获取当前位置的上一个节点
      let preNode = this.getNode(postion - 1)
      current.next = preNode.next
      preNode.next = current
    }
    this.size ++
  }
  /* 根据index 获取列表的节点 */
  getNode(index) {
    if(index < 0 || index >= this.size) {
      throw Error('index out range')
    }
    let current = this.head
    for(let i = 0; i < index; i++) {
      current = current.next
    }
    return current
  }
}
const ll = new MyList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.remove(2)
console.dir(ll,{
  depth: 4
});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值