js数据结构--栈(stack)

176 阅读1分钟

栈是一种遵从后的进先出原则的有序集合

github

  1. push(val) 添加一个新元素到栈顶
  2. pop() 移除栈的元素,同时返回被移除的元素
  3. peek() 返回栈顶的元素,不对栈做任何修改
  4. isEmpty() 如果栈里没有任何元素就返回true,否则返回false
  5. clear() 移除栈里的所有元素
  6. size() 返回栈里的元素个数

目录

inex.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='./stack.js'></script>
    <script src='./stack-es6.js'></script>
</head>
<body>
    aa
</body>
</html>

stack.js

var Stack = function(){
    var items = [];
    // this.items = [];
    this.push= function(val){
        items.push(val)
    }
    this.pop = function(){
        return items.pop()
    }
    this.peek = function(){
        return items[items.length-1]
    }
    this.isEmpty = function(){
        return items.length === 0
    }
    this.clear = function(){
        items = []
    }
    this.size= function(){
        return items.length
    }    
}

var s1 = new Stack()

var items = []this.items = []的区别: this.items是公有的,s1,s2都能访问得到

var s1 = new Stack()
var s2 = new Stack()

stack-es6.js

class StackEs6{
    constructor(){
        this.items = []
    }
    push(val){
        this.items.push(val)
    }
    pop(){
        return this.items.pop()
    }
    size(){
        return this.items.length
    }
    peek(){
        return this.items[this.items.length-1]
    }
    isEmpty(){
        return this.items.length === 0 
    }
    clear(){
        this.items = []
    }
    size(){
        return this.items.length
    }
}

var s2 = new StackEs6()

2种实现对比

实例,10进制转2进制

  1. 十进制数是组成以10为基础的数字系统,有0,1,2,3, 4, 5, 6, 7, 8, 9十个基本数字组成
  2. 二进制数(binaries)是逢2进位的进位制,0、1是基本算符

var tenToTwo = function(number){
    var s2 = new StackEs6()
    var remainder  //余数
    var str = '';
    while(number >0){
        remainder = number%2
        number =Math.floor(number/2)
        s2.push(remainder)
    }
    while(s2.isEmpty() === false){
        str+= s2.pop()
    }
    return str
}

栈的体现

function f1(){
    return console.log('f1 finish')
}

function f2(){
    f1()
    return console.log('f2 finish')
}