// 栈的基本特性实现
function Stack(){ this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.clear = clear; this.length = length; } function push(element){ this.dataStore[this.top++] = element; } function peek(){ return this.dataStore[this.top - 1]; } function pop(){ return this.dataStore[--this.top]; } function clear(){ this.top = 0; } function length(){ return this.top; } // 检查括号匹配 function checkBracket(expression){ var s = new Stack(); for (var i = 0; i < expression.length; ++i){ if (expression[i] == "("){ s.push(i+1); } else if(expression[i] == ")"){ s.pop(); } } if (s.length() > 0){ return s.pop(); } else { return -1; } } var ans = checkBracket("2.3+((((23/12+(3.14)159*0.24"); print("num:" + ans);
op1 op2 operator
使用两个栈,一个用来存储操作数,另一个用来存储操作符,设计并实现一个JavaScript函数,该函数可以将中缀表达式转换为后缀表达式,然后利用栈对该表达式求值。
function Stack(){ this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.clear = clear; this.length = length; } function push(element){ this.dataStore[this.top++] = element; } function peek(){ return this.dataStore[this.top - 1]; } function pop(){ return this.dataStore[--this.top]; } function clear(){ this.top = 0; } function length(){ return this.top; } // 计算输入表达式 function cal(expression){ var nums = new Stack(); var opreators = new Stack(); var exp = expression.split(" "); for (var i = 0; i < exp.length ; ++i){ if (i < exp.length - 1){ nums.push(exp[i]); } else{ opreators.push(exp[i]); } } var num1 = nums.pop(); // print(num1); var num2 = nums.pop(); // print(num2); var op = opreators.pop(); // print(op); var res = 0; switch (op){ case "+": res = parseFloat(num1) + parseFloat(num2); break; case "-": res = parseFloat(num1) - parseFloat(num2); break; case "*": res = parseFloat(num1) * parseFloat(num2); break; case "/": res = parseFloat(num1) / parseFloat(num2); break; } return { expStr:num1 + op + num2 + "=" + res.toString(), res: res }; } var expression = "12 15 +"; print(cal(expression).expStr);
function Stack(){ this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.clear = clear; this.length = length; } function push(element){ this.dataStore[this.top++] = element; } function peek(){ return this.dataStore[this.top - 1]; } function pop(){ return this.dataStore[--this.top]; } function clear(){ this.top = 0; } function length(){ return this.top; } var candies = new Stack(); candies.push("red"); candies.push("red1"); candies.push("yellow"); candies.push("yellow"); candies.push("blue"); candies.push("red"); candies.push("yellow"); candies.push("red"); var temp = new Stack(); while(candies.length()>0){ var candle = candies.pop(); if (candle != "yellow"){ temp.push(candle); } } while(temp.length()>0){ var candle = temp.pop(); candies.push(candle); } while(candies.length()>0){ var candle = candies.pop(); print(candle); }
原文:https://www.cnblogs.com/bloossoms/p/14063900.html