Exemple #1
0
        public bool combinarParenteses(string expressao)
        {
            Pilha <char> parenteses = new Pilha <char>();

            foreach (char c in expressao)
            {
                if (c == '(')
                {
                    parenteses.Empilhar(c);
                }
                else if (c == ')')
                {
                    try
                    {
                        parenteses.Desempilhar();
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
            }

            if (!parenteses.EstaVazia())
            {
                return(false);
            }

            return(true);
        }
Exemple #2
0
        public static Expressao TraduzirParaPosfixa(Expressao expressaoInfixa)
        {
            String infixa = expressaoInfixa.expressao;

            Pilha <char> p       = new Pilha <char>();
            String       posfixa = "";

            for (int i = 0; i < infixa.Length; i++)
            {
                bool unario = false;

                if (isOperador(infixa[i]))
                {
                    if (infixa[i] == '-')
                    {
                        if (i == 0 || infixa[i - 1] == '(')
                        {
                            p.Empilhar('@');
                            unario = true;
                        }
                    }

                    if (!unario)
                    {
                        bool parar = false;

                        while (!parar && !p.EstaVazia() && Precedencia(p.OTopo(), infixa[i]))
                        {
                            char operadorComMaiorPrec = p.OTopo();
                            if (operadorComMaiorPrec == '(')
                            {
                                parar = true;
                            }
                            else
                            {
                                posfixa += operadorComMaiorPrec;
                                p.Desempilhar();
                            }
                        }

                        if (infixa[i] != ')')
                        {
                            p.Empilhar(infixa[i]);
                        }
                        else
                        {
                            p.Desempilhar();
                        }
                    }
                }
                else
                {
                    posfixa += infixa[i];
                }
            }

            while (!p.EstaVazia())
            {
                char operadorComMaiorPrec = p.Desempilhar();
                if (operadorComMaiorPrec != '(')
                {
                    posfixa += operadorComMaiorPrec;
                }
            }

            return(new Expressao(posfixa, expressaoInfixa.dicionario));
        }