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
}

你可能感兴趣的:(js+链表)