用JS来实现一个栈

分别使用线性表和链表两种形式

//使用链表实现
function linkedStack(){
    var top;
    var length = 0;
    function Node(element){
        this.element = element;
        this.next = null;
    }
    this.push = function(element){
        var node = new Node(element);
        if(top){
            node.next = top;
            top = node;
            length++;
            return true;
        }else{
            top = node;
            length++;
            return true;
        }
    }
    this.pop = function(){
        if(top){
            var current;
            current = top;
            top = top.next;
            current.next = null;
            length--;
            return current;
        }else{
            return "stack empty"
        }
    }
    this.top = function(){
        return top;
    }
    this.length = function(){
        return length;
    }
    this.toString = function(){
        var string = '';
        var current = top;
        while(current){
            string += current.element;
            current = current.next;
        }
        return string;
    }
    this.clear = function(){
        top = null;
        length = 0;
        return true;
    }
}



//使用线性表实现
function Stack(){
    var stack = [];
    this.push = element =>stack.push(element);
    this.pop = ()=>stack.pop();
    this.length = ()=>stack.length;
    this.top = ()=>{
        if(stack.length){
            return stack[stack.length-1];
        }
        return "stack empty"
    }
    this.clear = ()=>{
        stack.length = 0;
        return true;
    }
    this.toString = ()=>{
        if(stack.length){
            stack.reverse();
            return stack.join(" "); 
        }
        return "stack empty"
        
    }
    
}

猜你喜欢

转载自blog.csdn.net/Mr_lizi/article/details/83998136