js实现栈和队列

113 阅读1分钟

思路

后进先出。
通过js的class实现。
封装push方法:
push方法就是简单地将接受的数据封装成对象,让其前一个对象等于当前栈顶对象,在让其栈顶为插入的这个对象。
封装pop方法:
返回栈顶对象的值,并将栈顶对象改变为栈顶对象的下一个对象。

代码

class Stack{
    size = 0
    head = null
    pop(){
        if(this.size>0){
            let result = this.head.value
            this.head = this.head.pre
            this.size--
            return result
        } else {
            return null
        }
    }
    push(v){
        let newNode = {
            pre: this.size==0?null:this.head,
            value: v
        }
        this.head = newNode
        this.size++
    }
    top(){
        return this.head.value
    }
}

队列

思路

跟栈很相似,不过为先进先出罢了。
封装push方法:
根据接收值封装成对象,当队列为空时,插入新值头和尾都为当前插入对象。否则从尾部插入。
封装unshift方法:
与栈的pop方法类似,只不过从另一端取值。

代码

class Queen{
    size = 0
    trail = {
        next: null,
        value: null
    }
    head = this.trail
    push(value){
        let newNode = {
            next: null,
            value
        }
        if(this.size>0){
            this.trail.next = newNode
            this.trail = this.trail.next
        } else {
            this.trail = newNode
            this.head = this.trail
        }
        this.size++
    }
    unshift(){
        if(this.size>0) {
            this.size--
            let result = this.head.value
            this.head = this.head.next
            return result
        }
        return null
    }
}

注意点

需要注意的是临界点值的处理,也就是当栈和队列为空是队数据增删的处理。