js实现单链表及各种操作

// 新建节点
class Node {
  constructor(val) {
    this.value = val
    this.next = null
  }
}
// 单向链表
class LinkedList {
  constructor(val) {
    this.length = 0
    this.head = null
  }
  // 新增节点
  append(val) {
    let newNode = new Node(val)
    if (this.head === null) {
      this.head = newNode
    } else {
      let p = this.head
      while (p.next) {
        p = p.next
      }
      p.next = newNode
    }
    this.length++
  }
  // 在某位置插入新值
  insert(index, val) {
    if (index < 0 || index > this.length - 1) {
      return false
    }
    let newInsertNode = new Node(val)
    let current = this.head
    let currIndex = 0
    if (index === 0) {
      newInsertNode.next = current
      this.head = newInsertNode
    } else {
      let pre = null
      while (currIndex < index) {
        pre = current
        current = current.next
        currIndex++
      }
      newInsertNode.next = current
      pre.next = newInsertNode
    }
    this.length++
    return true;
  }

  //根据位置删除指定节点,成功返回元素,失败返回null
  removeAt(position) {
    if (position >= 0 && position < this.length) {
      var current = this.head //current指针用来指向该指定节点
      var previous = null //previous指针指向current指针前一个节点
      var index = 0 //纪录是否到达指定位置
      if (position == 0) {
        this.head == current.next
      } else {
        while (index < position) {
          previous = current //每次将previous指针和current指针向后移动一个,直到到达指定节点
          current = current.next
          index++
        }
        previous.next = current.next //该指定节点的前一个指针越过指定节点,直接指向其下一个节点
      }
      this.length-- //别忘了更新链表长度
      return current.val //返回该元素
    } else {
      return null
    }
  }

  //根据元素删除指定元素,成功返回已删除的节点,失败返回null
  remove(val) {
    let index = this.find(val)
    return this.removeAt(index)
  }

  //根据元素查找节点,成功返回给定元素的索引,如果没有则返回-1
  find(val) {
    var current = this.head
    var index = 0
    if (current.val == val) {
      return 0
    }
    while (current) {
      if (current.val == val) {
        return index
      }
      current = current.next
      index++
    }
    return -1
  }

  isEmpty() {
    return this.length == 0
  }

  size() {
    return this.length
  }

  toString() {
    let str = ''
    let current = this.head
    while (current) {
      str += ',' + current.val
      current = current.next
    }
    return str
  }
}
let newList = new LinkedList()
newList.append('1')
newList.append('2')
newList.insert(1, 4)
console.log(JSON.stringify(newList));

原文链接:https://blog.csdn.net/weixin_43221323/article/details/106241314

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值