JavaScript数据结构与算法Day6

88 阅读1分钟

链表剩下的常用操作

  • get方法
LinkedList.prototype.get = function (position) {
                if (position < 0 || position >= this.length) return null
                var current = this.head
                var index = 0
                while (index++ < position) {
                    current = current.next
                }
                return current.data
            }
  • indexOf方法
LinkedList.prototype.indexOf = function (data) {
                var current = this.head
                var index = 0
                while (current) {
                    if (current.data == data) {
                        return index
                    }
                    current = current.next
                    index += 1
                }
                return -1
            }
  • update方法
LinkedList.prototype.update = function (position, newdata) {
                if (position < 0 || position >= this.length) return false
                var current = this.head
                var index = 0
                while (index++ < position) {
                    current = current.next
                }
                current.data = newdata
                return true
            }
  • removeAt方法
LinkedList.prototype.removeAt = function (position) {
                if (position < 0 || position >= this.length) return false
                var current = this.head
                var previous = null
                if (position == 0) {
                    this.head = this.head.next
                    this.length -= 1
                    return current.data
                } else {
                    var index = 0
                    while (index++ < position) {
                        previous = current
                        current = current.next
                    }
                    previous.next = current.next
                    this.length -= 1
                    return current.data
                }
            }
  • remove方法
LinkedList.prototype.remove = function (data) {
                var position = this.indexOf(data)
                return this.removeAt(position)
            }
  • isEmpty方法
LinkedList.prototype.isEmpty = function () {
                return this.length == 0
            }
  • size方法
LinkedList.prototype.size = function () {
                return this.length
            }

双向链表

  • 单向链表只能从头到尾遍历,但不能从这个节点回到上一个节点
  • 双向链表既可以从头到尾也可以从尾到头
  • 有向后的引用也有向前的引用
  • 虽然占用内存稍微大点,但瑕不掩瑜