先声明一个栈类:Stack.js
function Stack(){
this.data = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
function push(element){
this.data[this.top++] = element;
console.log("In push function this.top is " + this.top);
}
function pop(){
if(this.top > 0){
var deletedElement = this.data[--this.top];
console.log("this.top is " + this.top);
delete this.data[this.top];
return deletedElement;
}
return;
}
function peek(){
//查看栈顶元素
return this.data[this.top - 1];
}
//清空一个栈
function clear(){
this.top = 0;
}
function length(){
return this.top;
}
module.exports = Stack;
2:利用栈处理表达式:main.js
var Stack = require("./Stack");
var numString = "2.3+23/12+(3.1459*0.24)";
console.log(numString.slice(0,3));
console.log(numString);
console.log(3- undefined);
function calculate(numString){
//数字栈
var numStack = new Stack();
//操作符栈
var operationStack = new Stack();
//将数组进行分割,成为数组
var tokens = insertBlank(numString).split(" ");
console.log("tokens is " + tokens);
//遍历这些数组
for(var m in tokens){
//将多出来的空格给消除掉针对输入数字操作符的时候有空格
if(tokens[m] === ''){
continue;
}else if(tokens[m].charAt(0) === '+' || tokens[m].charAt(0)=== '-'){
//处理所有的操作符
while((operationStack.length() != 0) &&
(operationStack.peek() === '+' ||
operationStack.peek() === '-' ||
operationStack.peek() === '*' ||
operationStack.peek() === '/')){
//操作符栈中有东西继续处理
processAnOperator(numStack,operationStack);
}
//将当前的操作符push进栈中去
operationStack.push(tokens[m].charAt(0));
}else if(tokens[m].charAt(0) === '*' || tokens[m].charAt(0) === '/'){
while(operationStack.length() != 0 &&(operationStack.peek() === '*' || operationStack.peek() === '/')){
//如果遇到乘除操作符进行处理
processAnOperator(numStack,operationStack);
}
operationStack.push(tokens[m].charAt(0));
}else if(tokens[m].trim().charAt(0) === '('){
operationStack.push('(');
}else if(tokens[m].trim().charAt(0) === ')'){
while(operationStack.peek() != '('){
//处理操作符直到遇到(
processAnOperator(numStack,operationStack);
}
//将(操作符移除栈
operationStack.pop();
}else{
//将操作数放到操作数栈中
numStack.push(parseFloat(tokens[m]));
}
}
while(operationStack.length() != 0){
processAnOperator(numStack,operationStack);
}
return numStack.pop();
}
//处理操作符方法
function processAnOperator(numStack,operationStack){
var op = operationStack.pop();
var num1 = numStack.pop();
var num2 = numStack.pop();
if(op === '-'){
numStack.push(num2 - num1);
}else if(op === '+'){
numStack.push(num2 + num1);
}else if(op === '*'){
numStack.push(num2 * num1)
}else{
numStack.push(num2 / num1);
}
}
//对所有的字符串进行加空格处理以便后续的分割数组
function insertBlank(numString){
var blankString = "";
for(var i = 0;i < numString.length;i++){
var indexOfI = numString[i];
if(indexOfI === '+' ||indexOfI === '-' ||
indexOfI === '*' ||indexOfI === '/' ||
indexOfI === '(' ||indexOfI === ')'){
blankString += ' ' + numString.charAt(i) + ' ';
}else{
blankString += numString.charAt(i);
}
}
return blankString;
}
var resr = calculate(numString);
console.log("result is " + resr);