栈是一种遵从后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称为栈顶,另一端称为栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。
class Stack { constructor(){ this.items = [] } } Stack.prototype.push = function(element){ this.items.push(element) } Stack.prototype.pop = function(){ return this.items.pop() } //返回栈顶元素,不对栈做任何修改 Stack.prototype.peek = function(){ return this.items[this.items.length-1] } Stack.prototype.isEmpty = function(){ return this.items.length == 0 } Stack.prototype.clear = function(){ this.items = [] } Stack.prototype.size = function(){ return this.items.length }
创建一个基于JavaScript对象的Stack类
class Stack { constructor(){ this.count = 0 this.items = {} } } Stack.prototype.push = function(element){ this.items[this.count] = element this.count++ } Stack.prototype.isEmpty = function(){ return this.count == 0 } Stack.prototype.size = function(){ return this.count } Stack.prototype.pop = function(){ if(this.isEmpty){ return undefined } this.count-- const result = this.items[this.count] delete this.items[this.count] return result } Stack.prototype.peek = function(){ if(this.isEmpty){ return undefined } return this.items[this.count-1] } Stack.prototype.clear = function(){ this.items = {} this.count = 0 // while(!this.isEmpty()){ // this.pop() // } } Stack.prototype.toString = function(){ if(this.isEmpty){ return '' } let str = `${this.items[0]}` for(let i = 1;i < this.count;i++){ str = `${str},${this.items[i]}` } return str }
十进制转二进制
function decimalToBinary(decNumber){ let number = decNumber const s = new Stack() let rem; let binaryStr = '' while(number > 0){ rem = Math.floor(number%2) s.push(rem) number = Math.floor(number/2) } while(!s.isEmpty()){ binaryStr += s.pop().toString() } return binaryStr }