数据结构——背包,队列,栈

后进先出

//js
let stack=[];
stack.push("1");//stack=[1]
stack.push("2");//stack=[1,2]
re=stack.pop();//re=2;stack=[1]
定容栈

定义一个空栈,有保存栈中元素的数组,一个元素数量的整数

function stack(array){
    if(array==undefined){
        this.array=[];  
    }else{
        this.array=array;
    }   
    this.n=array.length;
}
stack.prototype.push=function(){
    this.array.push(arguments[0]);
    this.n+=1;
    return this.array.slice();
}
stack.prototype.pop=function(){
    this.n-=1;
    return this.array.pop();
}

背包

背包是一种不支持从中删除元素的集合数据类型,它的作用是帮助用例收集元素并迭代遍历所有收集到的元素(也可以检查背包是否为空或者背包中元素的数量)。使用背包说明元素的处理顺序不重要。
背包样例://加值和求平均

function Bag(array){
    this.number=array.slice();//获取array的副本
}
Bag.prototype.add=function(){
    for(let i=0;i<arguments.length;i++){
        if(typeof arguments[i]=="object"){
            this.add.apply(this,arguments[i]);
        }else{
            this.number.push(arguments[i]);
        }
    }
    return this.number.slice();//防止通过其他方法修改bag的数据
}
Bag.prototype.ave=function(){
    var count=0;
    this.number.map(num=>count+=num);
    return count/this.number.length;
}

队列

先进先出

function Queue(){
    this.number=[];
}
Queue.prototype.enqueue=function(){
    this.number.push(arguments[0]);
    return this.number.slice();
}
Queue.prototype.dequeue=function(){
    return this.number.unshift();
}

链表

链表是一种递归的数据结构,它或者为空(null),或者指向一个结点(node)的引用,该结点含有一个泛型的元素和一个指向另一条链表的引用。
定义结点的抽象类型

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

基于链表的栈

优点:
* 所需的空间总是与集合的大小成正比
* 操作所需时间总是和集合的大小无关

function Node(item){
    this.item=item;
    this.next=null;
}
function Stack(){
    this.first=null;
    this.n=0;
}
Stack.prototype.push=function(item){
    let node=new Node(item);
    this.n++;
    if(this.first){     
        node.next=this.first;
        this.first=node;
    }else{
        this.first=node;
    }   
}
Stack.prototype.pop=function(){
    let node=this.first;
    if(node==null){
        return null;
    }
    this.first=node.next;
    return node.item;
}

基于链表的队列

//节点参考上面
function Queue(){
    this.first=null;
    this.tail=null;
    this.n=0;
    this.Empty=function(){return this.first==null};
    this.size=function(){return this.n};
}
Queue.prototype.enQueue=function(item){
    let node=new Node(item);
    if(this.first==null){
        this.first=node;
    }
    this.tail.next=node;
    this.tail=node;
    this.n++;
}
Queue.prototype.deQueue=function(){
    if(this.first==null){
        return null;
    }
    let node=this.first;
    this.first=node.next;
    return node.item;
}

猜你喜欢

转载自blog.csdn.net/lay136362687/article/details/81199251