数据结构(栈的封装)

114 阅读1分钟

栈:一种遵循后进先出(LIFO)原则的有序集合。

下面是我在学习栈过程中,封装的栈数据结构

// 创建一个栈类
        class Stack {
            constructor(){
                // 表示栈中元素的个数
                this.count = 0;
                // 栈中的元素都储存在这个对象中
                this.item = {};
            }

            //push方法
            push(e) {
                this.item[this.count] = e;
                this.count++;
            }
            //size方法
            size() {
                return this.count;
            }
            // 是否为空方法
            isEmpty() {
                return this.count === 0;
            }
            // 从栈中弹出元素(删除元素)
            pop() {
                if(this.isEmpty()) {
                    return undefined;
                }else { 
                    this.count--;
                    let res = this.item[this.count];
                    delete this.item[this.count];
                    return res;
                }

            }
            // 查看栈顶的值
            peek() {
                if(this.isEmpty()) {
                    return undefined;
                }else {
                    // 这里不可以这样写  this.item[this.count--] 
                    this.count--
                    return this.item[this.count];
                }
            }
            // 清空栈
            clear() {
                this.count=0
                this.item = {}
            }
            // toString方法
            toString() {
                if(this.isEmpty()) {
                    return ''
                }else{
                    let str =''
                    // 这里使用for in遍历对象 也可以用普通的for循环来进行便利 而且当数据超级大的时候,for循环的速度更快,性能更好
                    for(let key in this.item) {
                        str += this.item[key]
                    }
                    return str
                }
            }
        } 
        let s = new Stack()
        s.push("one")
        s.push("two")
        s.push("there")
        console.log(s.toString());
        // console.log(s.peek());

这只是简单的封装了一个栈数据结构,这里我使用的是对象的方法来保存栈中的数据结构,也可以使用数组来封装。 参考书籍:《学习JacaScript数据结构与算法》(第三版)