JS算法与数据结构-列表

constructor() {
            //数组长度
            this.listSize = 0;
            // 初始化一个空数组来保存列表元素
            this.dataStore = [];
            //指针
            this.pos = 0;
        }
        // append :给列表添加元素
        append(element) {
            this.dataStore[this.listSize++] = element;
        }
        // remove :从列表中删除元素
        find(element) {
            for (var i = 0; i < this.dataStore.length; ++i) {
                if (this.dataStore[i] == element) {
                    return i;
                }
            }
            return -1;
        }
        remove(element) {
            var foundAt = this.find(element);
            if (foundAt > -1) {
                this.dataStore.splice(foundAt, 1);
                //删除了元素列表长度就要减1了
                --this.listSize;
                return true;
            }
            return false;
        }
        // length :列表中有多少个元素
        length() {
            return this.listSize;
        }
        // toString :显示列表中的元素
        toString() {
            return this.dataStore;
        }
        //insert :向列表中插入一个元素
        insert(element, after) {
            var insertPos = this.find(after);
            if (insertPos > -1) {
                this.dataStore.splice(insertPos + 1, 0, element);
                ++this.listSize;
                return true;
            }
            return false;
        }
        // clear :清空列表中所有的元素
        clear() {
            delete this.dataStore;
            this.dataStore = [];
            this.listSize = this.pos = 0;
        }
        // contains :判断给定值是否在列表中
        contains(element) {
            for (var i = 0; i < this.dataStore.length; ++i) {
                if (this.dataStore[i] == element) {
                    return true;
                }
            }
            return false;
        }
        //
        front() {
            this.pos = 0;
        }
        end() {
            this.pos = this.listSize - 1;
        }
        prev() {
            if (this.pos > 0) {
                --this.pos;
            }
        }
        next() {
            if (this.pos < this.listSize - 1) {
                ++this.pos;
            }
        }
        currPos() {
            return this.pos;
        }
        moveTo(position) {
            this.pos = position;
        }
        getElement() {
            return this.dataStore[this.pos];
        }

    }

你可能感兴趣的:(JS算法与数据结构-列表)