"infix to postfix converter" Code Answer

4

if you replace array by a stack<string>, you don't have to keep track where you are with the index variable.

you can then return your result with postfixstack.toarray()

my implementation:

public static string[] infixtopostfix( string[] infixarray )
{
    var stack = new stack<string>();
    var postfix = new stack<string>();

    string st;
    for ( int i = 0 ; i < infixarray.length ; i++ )
    {
        if ( !( "()*/+-".contains( infixarray[ i ] ) ) )
        {
            postfix.push(infixarray[i]);
        }
        else
        {
            if ( infixarray[ i ].equals( "(" ) )
            {
                stack.push( "(" );
            }
            else if ( infixarray[ i ].equals( ")" ) )
            {
                st = stack.pop();
                while ( !( st.equals( "(" ) ) )
                {
                    postfix.push( st );
                    st = stack.pop();
                }
            }
            else
            {
                while ( stack.count > 0 )
                {
                    st = stack.pop();
                    if ( regneprioritet( st ) >= regneprioritet( infixarray[ i ] ) )
                    {
                        postfix.push(st);
                    }
                    else
                    {
                        stack.push( st );
                        break;
                    }
                }
                stack.push( infixarray[ i ] );
            }
        }
    }
    while ( stack.count > 0 )
    {
        postfix.push(stack.pop());
    }

    return postfix.reverse().toarray();
}
By Nick Corin on March 27 2022

Answers related to “infix to postfix converter”

Only authorized users can answer the Search term. Please sign in first, or register a free account.