static Queue <Token> Infix2Postfix(TokenList infix) { Queue <Token> postfix = new Queue <Token>(); Stack <Token> opStack = new Stack <Token>(); while (true) { Token token = infix.First; if (token != null) { if (token.Type == Tokens.Number || token.Type == Tokens.Variable) { postfix.Enqueue(token); } else if (token.Type == Tokens.Function) { opStack.Push(token); } else if (token.Type == Tokens.Comma) { while (opStack.Peek().Type != Tokens.LB) { postfix.Enqueue(opStack.Pop()); } } else if (token.Type == Tokens.Operator) { while (opStack.Count > 0 && opStack.Peek().Type == Tokens.Operator && Operators.Precedence(opStack.Peek().Name) >= Operators.Precedence(token.Name)) { postfix.Enqueue(opStack.Pop()); } opStack.Push(token); } else if (token.Type == Tokens.LB) { opStack.Push(token); } else if (token.Type == Tokens.RB) { while (opStack.Peek().Type != Tokens.LB) { postfix.Enqueue(opStack.Pop()); } opStack.Pop(); if (opStack.Count > 0 && opStack.Peek().Type == Tokens.Function) { postfix.Enqueue(opStack.Pop()); } } } else { while (opStack.Count > 0) { postfix.Enqueue(opStack.Pop()); } break; } infix.RemoveAt(0); } return(postfix); }
public void AddRange(TokenList collection) { list.AddRange(collection.list); }
static TokenList Input2List(string input) { TokenList infix = new TokenList(); for (int i = 0; i < input.Length; i++) { if (input[i].isDigit() || (input[i] == '-' && (infix.Last == null || infix.Last.Type != Tokens.Number))) { StringBuilder s = new StringBuilder(); s.Append(input[i]); while (i + 1 < input.Length && (input[i + 1].isDigit() || input[i + 1].isSpace() || input[i + 1].isDot())) { if (!input[++i].isSpace()) { s.Append(input[i]); } } infix.Add(Tokens.Number, s); continue; } else if (input[i].isLetter()) { StringBuilder s = new StringBuilder(); s.Append(input[i]); while (i + 1 < input.Length && (input[i + 1].isLetter() || input[i + 1].isDigit())) { s.Append(input[++i]); } if (i + 1 < input.Length && input[i + 1] == '(') { i++; StringBuilder inception = new StringBuilder(); int brackets = 1; int commas = 0; while (brackets > 0) { i++; if (i > input.Length) { throw new Exception("brackets don't balanced"); } if (input[i] == '(') { brackets++; } else if (input[i] == ')') { brackets--; } if (brackets > 0) { inception.Append(input[i]); } if (input[i].isComma() && brackets == 1) { commas++; } } if (inception.Length == 0) { infix.Add(Tokens.Function, s.Append(0)); } else { infix.Add(Tokens.Function, s.Append(commas + 1)); } infix.Add(Tokens.LB, '('); infix.AddRange(Input2List(inception.ToString())); infix.Add(Tokens.RB, ')'); } else { infix.Add(Tokens.Variable, s); } continue; } else if (input[i].isOperator()) { infix.Add(Tokens.Operator, input[i]); } else if (input[i] == '(') { infix.Add(Tokens.LB, '('); } else if (input[i] == ')') { infix.Add(Tokens.RB, ')'); } else if (input[i] == ',') { infix.Add(Tokens.Comma, ','); } } if (!infix.BracketsBalance()) { throw new Exception("Brackets don't balanced"); } return(infix); }