数据结构——栈(JavaScript)

栈是一种遵从后进先出(LIFO)原则的有序集合。新添加的或待删除的元素都保存在栈的 末尾,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。

举个栗子,差不多这样子。。。
这里写图片描述

栈的创建

使用数组创建的栈

function Stack(){//首先,申明一个类
    var item = []; //使用一种数据结构来保存栈内元素
    //声明常用方法
    this.push = function(v){//添加一个(或几个)新元素到栈顶 
        item.push(v);
    }
    this.pop = function(){//移除栈顶的元素,同时返回被移除的元素
        return item.pop();
    }
    this.peek = function(){//返回栈顶的元素,不对栈做任何修改
        return item[item.length-1];
    }
    this.isEmpty = function(){//如果栈里没有任何元素就返回true,否则返回false
        return !item.length;
    }
    this.clear = function(){//移除栈里的所有元素
        item = [];
    }
    this.size = function(){//返回栈里的元素个数
        return item.length;
    }
    this.print = function(){
        console.log(item.toString());
    }
}

使用链表创建的链栈

这里写图片描述

function Stack(){//首先,申明一个类
    //使用链表节点来保存栈内元素
    var Node = function(value){
        this.value = value;
        this.next = null;
    }
    //初始化栈的高度以及栈顶指针
    var length = 0;
    var top = null;
    //声明常用方法
    this.push = function(v){//添加一个(或几个)新元素到栈顶 
        var newNode = new Node(v);
        if(!top){
            top = newNode;
        }else{//头插
            newNode.next = top;
            top = newNode;
        }
        length++;
        return top;
    }
    this.pop = function(){//移除栈顶的元素,同时返回被移除的元素
        if (!top) {
            alert("Empty stack");
            return ;
        } else{
            var t = top;
            top = top.next;
            t.next = null;
            length--;
            return top;
        }
    }
    this.peek = function(){//返回栈顶的元素,不对栈做任何修改
        return top.value;
    }
    this.isEmpty = function(){//如果栈里没有任何元素就返回true,否则返回false
        return !length;
    }
    this.clear = function(){//移除栈里的所有元素
        top = null;
        length = 0;
        return top;
    }
    this.size = function(){//返回栈里的元素个数
        return length;
    }
    this.print = function(){
        var t = top;
        var result = [];
        while(t){
            result.unshift(t.value);
            t = t.next;
        }
        console.log(result);
        return;
    }
}

栈的基本使用

var stack = new Stack();
console.log(stack.isEmpty()); //true
stack.push(1);
stack.push(2);
console.log(stack.size());  //2
stack.push(3);
console.log(stack.peek());  //3
stack.pop();
stack.print();  //1,2
stack.clear();  
console.log(stack.isEmpty());   //true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值