// 定义一个栈的类 实现栈的push pop getMax getMin等函数 // 并实现先进后出 后进先出 而且能够不断求出 当前栈里面的数据的最大值最小值classStack{constructor(){this.dataStack=[];this.maxStack=[];this.minStack=[];}// 入栈push(item){if(this.minStack.length<=0){this.minStack.push(item)}elseif(item<=this.getMin()){this.minStack.push(item)}if(this.maxStack.length<=0){this.maxStack.push(item)}elseif(item>=this.getMax()){this.maxStack.push(item)}this.dataStack.push(item);}// 出栈pop(){if(this.dataStack.length<=0){return}letvalue=this.dataStack.pop();if(value==this.getMin()){this.minStack.pop()}if(value==this.getMax()){this.maxStack.pop();}returnvalue;}// 求最小值getMin(){if(this.minStack.length<=0){return0;}returnthis.minStack[this.minStack.length-1];}// 求最大值getMax(){if(this.maxStack.length<=0){return0;}returnthis.maxStack[this.maxStack.length-1];}}// 创建栈的对象varstack=newStack();// 调用入栈stack.push(3);stack.push(5);stack.push(10);stack.push(7);stack.push(6);// 调用求最大值 最小值的函数console.log(stack.dataStack);console.log(stack.getMax());console.log(stack.getMin());// 出栈stack.pop();stack.pop();// 出栈后的最大值最小值console.log(stack.getMax());console.log(stack.getMin());console.log(stack.minStack);console.log(stack.maxStack);stack.pop();console.log(stack.getMax());console.log(stack.getMin());console.log(stack.minStack);console.log(stack.maxStack);stack.pop();console.log(stack.getMax());console.log(stack.getMin());console.log(stack.dataStack);console.log(stack.maxStack);stack.pop();console.log(stack.getMax());console.log(stack.getMin());console.log(stack.dataStack);console.log(stack.maxStack);
网友评论