JavaScript 实现栈结构

栈是一种数据结构,其特点是先进后出,后进先出的一种特征。我们遇到只在一头操作,并且是采用先进后出,后进先出的原则,我们可以优先考虑栈结构。

顺序栈

function Stack() {
    this.data = [];
    this.count = 0;
}
Stack.prototype = {
    push: function(element) {
        this.data[this.count] = element;
        ++this.count;
        return true;
    },

    pop: function() {
        if (this.count == 0) return null;
        var tmp = this.data[this.count - 1];
        --this.count;
        return tmp;
    },

    peek: function() {
        return this.data[this.count - 1];
    },

    isEmpty: function() {
        return this.count == 0;
    },

    size: function() {
        return this.count;
    },

    print: function() {
        let result = '';
        for (let i of this.data) {
            result = result + '=>' + i;
        }
        return result;
    },

    clear: function() {
        this.count = 0;
    }
}

Stack.prototype.constructor = Stack;

链式栈

function Node(data) {
    this.data = data;
    this.next = null;
}

function ListStack() {
    this.head = new Node('head');
    this.count = 0;
}

ListStack.prototype = {
    push: function(element) {
        var head = this.head;
        var newNode = new Node(element);
        newNode.next = head.next;
        head.next = newNode;
        ++this.count;
    },
    
    pop: function() {
        var head = this.head;
        if (!head.next) return '节点不存在';
        head.next = head.next.next;
        --this.count;
        return head.next;
    },
    
    peek: function() {
        return this.head.next;
    },

    isEmpty: function() {
        return this.count == 0;
    },

    size: function() {
        return this.count;
    },

    print: function() {
        var result = '';
        var head = this.head;
        while (head.next) {
            result = result + '=>' + head.next
        }
        return result;
    },

    clear: function() {
        this.count = 0;
        this.head.next = null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值