JavaScript数据结构与算法Day5

122 阅读1分钟

链表结构的封装

function LinkedList(){
        //内部类 节点Node
        function Node(data){
            this.data = data
            this.next = null
        }
        //属性
        this.head = null
        this.length = 0
    }

实现链表常见操作

追加append方法

  • 新建节点
  • 判断是否是第一个节点
  • 如果是就将head指向这个节点
  • 如果不是就用while找到最后一个节点
  • 最后一个节点的next指向新建节点
  • 链表长度加1
LinkedList.prototype.append = function (data) {
        var newNode = new Node(data)
        if(this.length == 0){
            this.head = newNode
        }else{
            var current = this.head
            while(current.next){
                current = current.next
            }
            current.next = newNode
        }
        this.length += 1
        }

toString方法

LinkedList.prototype.toString = function () {
                var current = this.head
                var listString = ''
                while(current){
                    listString += current.data + ' '
                    current = current.next
                }
                return listString
            }

insert插入方法

LinkedList.prototype.insert = function (position, data) {
                if (position < 0 || position > this.length) return false
                var newNode = new Node(data)
                var previous = null
                var current = this.head
                if (position == 0) {
                    newNode.next = this.head
                    this.head = newNode
                } else {
                    var index = 0
                    while (index++ < position) {
                        previous = current
                        current = current.next
                    }
                    newNode.next = current
                    previous.next = newNode
                }
                this.length += 1
                return true
            }