js+链表

链表结构

function Node(val, next){
  this.val = val
  this.next = next || null
}

function LinkedList(head){
  this.head = head || null
}

## 链表中插入节点
```js
LinkedList.prototype.insert = function(index, data){
  if (index < 0) return
  if (index == 0){   //插在头部
    this.head = new Node(data, this.head)
    return
  }
  var p = this.head
  var post
  var j = 0
  while (j < index){
    post = p
    if(!p) throw new Error("链表没那么长")
    p = p.next
    j += 1
    if (index == j){
      q = new Node(data, p)
      post.next = q
    }
  }
}

删除链表某节点

LinkedList.prototype.remove = function(index){
  if (index < 0) return
  var result
  if (index == 0) {   //删除头
    result = this.head.val
    this.head = this.head.next
    return result
  }
  var p = this.head
  var j = 0
  while (j < index - 1){
    p = p.next
    if(!p || !p.next) throw new Error("链表没那么长")
    j += 1
  }
  result = p.next.data
  p.next = p.next.next
  return result
}

遍历

LinkedList.prototype.getAllData = function(){
  p = this.head
  var result = []
  while(p){
    result.push(p.val)
    p = p.next
  }
  return result
}

反转单链表

LinkedList.prototype.reverse = function(){
  if (!this.head || !this.head.next){return}
  var cur = this.head
  var pre = null
  var tmp
  while (cur){
    tmp = cur.next
    cur.next = pre
    pre = cur
    cur = tmp
  }
  this.head = pre
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【声明】欢迎转载,但请保留文章原始出处→_→文章来源:http://www.jianshu.com/p/08d08...
    梦工厂阅读 9,171评论 3 31
  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 10,639评论 0 12
  • 本文内容:1、 什么是链表?2、 链表共分几类?3、 链表的 C 实现! 总表:《数据结构?》 工程代码 Gith...
    半纸渊阅读 40,163评论 0 54
  • 大学的时候不好好学习,老师在讲台上讲课,自己在以为老师看不到的座位看小说,现在用到了老师讲的知识,只能自己看书查资...
    和珏猫阅读 5,342评论 1 3
  • //leetcode中还有花样链表题,这里几个例子,冰山一角 求单链表中结点的个数----时间复杂度O(n)这是最...
    暗黑破坏球嘿哈阅读 5,450评论 0 6

友情链接更多精彩内容