链表-单向链表&双向&循环

2017-06-14  本文已影响0人  Ann_l
单向链表

总结:链表就相当于一个盒子里有2个数据,一个是元素,另一个是下一个盒子的元素。这段代码敲下来,我觉得比较特别的是删除元素。以前想删除元素一定要用splice,但是链表,你只需要将指向替换就行了。

function LList() {
  this.head = new Node('head')
  this.find = find
  this.insert = insert
  this.remove = remove
  this.findPrevious=findPrevious
  this.display = display
}
function Node(element) {
  this.element = element
  this.next = null
}

function find(item) {
  var currNode = this.head
  while (currNode.element !== item) {
    currNode = currNode.next
  }
  return currNode
}
function insert(newElement, item) {
  var newNode = new Node(newElement)
  var current = this.find(item)
  newNode.next = current.next
  current.next = newNode
}
function display() {
  var currNode = this.head
  while (!(currNode.next === null)) {
    console.log(currNode.next.element)
    currNode = currNode.next
  }
}
function findPrevious(item) {
  var currNode = this.head
  while (!(currNode.next === null) && (currNode.next.element !== item)) {
    currNode = currNode.next
  }
  return currNode
}
function remove(item) {
  var prevNode = this.findPrevious(item)
  if (!(prevNode.next === null)) {
    prevNode.next = prevNode.next.next
  }
}
var cities = new LList()
cities.insert('conway', 'head')
cities.insert('Russ', 'conway')
cities.insert('ann', 'Russ')
cities.display()//conway Russ ann

cities.remove('Russ')
cities.display()//conway  ann
双向链表
循环链表
上一篇 下一篇

猜你喜欢

热点阅读