Js实现单链表操作

单链表

// 链表

//  创建节点的构造函数
function Node(element) {
  this.element = element
  // 初始的节点的next指向都为 null
  this.next = null
}

// 创建 链表类
function LList() {
  // 链表类的第一个头节点
  this.head = new Node("head")
}

// 链表类的原型方法
LList.prototype = {
  constructor: LList,
  // 按值查找
  find: function (item) {
    // 从头节点开始寻找
    var currNode = this.head
    if (item === null) return
    while (currNode.element != item) {
      currNode = currNode.next
    }
    return currNode
  },
  // 前插法
  Preinsert: function (newEel, item) {
    var newNode = new Node(newEel)
    var current = this.find(item)
    // 将当前节点的next指向新节点
    // 例:current.next -> x,新节点 newNode.next ->null
    // newNode.next -> x ,Current.next -> newNode
    newNode.next = current.next
    // 将新节点的值给当前节点
    current.next = newNode
  },
  // 后插法
  nextInsert: function (newEel) {
    var currNode = this.head
    var newNode = new Node(newEel)
    //找到最后一个元素
    while (currNode.next !== null) {
      currNode = currNode.next
    }
    // 将最后一个元素当成前缀开始插入
    var endNode = currNode
    //例子 end为最后的元素
    // end.next -> 新元素 
    // 新元素 则变成最后一个元素,一次类推
    endNode.next = newNode
    endNode = newNode
  },
  //显示链表
  display: function () {
    var current = this.head
    while (current.next !== null) {
      console.log(current.next)
      current = current.next
    }
  },
  // 查找前一项
  findPre: function (item) {
    var currNode = this.head
    while (!(currNode.next === null) && currNode.next.element != item) {
      currNode = currNode.next
    }
    return currNode
  },
  remove: function (item) {
    var preItem = this.find(item)
    if (preItem.next !== null) {
      preItem.next = preItem.next.next
    } else {
      console.log(false)
    }
  },
}
var cities = new LList()
cities.Preinsert("Conway", "head")

cities.nextInsert("God")
cities.nextInsert('Aglet')
cities.display()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值