JavaScript实现栈数据结构

栈的介绍

栈是和链表相似的数据结构,相对来说更加的高效,因为它只能在栈顶进行插入和删除操作,实现起来更加的简单,而且很快。从表达式求值到函数的调用,都可以看到栈的使用。栈这种数据结构,我们可以具体的类似于餐厅里面的一叠盘子,每次我们取盘子都只能从最上面拿,放盘子只能放在最上面,所以栈是一种先入后出的数据结构。具体的操作有pop()入栈,push()出栈peek()方法只访问栈顶的元素,但是不删除它。下面看具体的实现方法。

//datastore保存元素,top记录栈顶的位置
function stack() {
    this.dataStore = [];
    this.top       = 0;
    this.push      = push;
    this.pop       = pop;
    this.peek      = peek;
    this.length    = length;
    this.clear     = clear;
}

function push( element ) {
    this.dataStore[ this.top++ ] = element;
    //this.dataStore.push(  )
}

function pop() {
    return this.dataStore[--this.top];
}

function peek() {
    return this.dataStore[ this.top - 1 ];
}

function length () {
    return this.top;
}

function clear () {
    this.top = 0 ;
}

//测试用例
// var stack = new stack();
// stack.push("dafei");
// stack.push("dafei2");
// stack.push('dafei3');
// console.log( stack.length() );
// console.log( stack.peek() );
// var pop =  stack.pop()
// console.log( pop );
// console.log( stack.peek() );
// stack.clear();
// console.log( stack.length() )
// console.log( stack.peek() );

使用栈进制转换

function mulBase ( num , base ) {
    var s = new stack();
    do {
        s.push(num%base);
        num = Math.floor( num /= base );
    } while( num > 0 );
    var rel = "";
    while( s.length() > 0 ) {
        rel += s.pop();
    }
    return rel;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值