Application of the stack - and reverse output matching brackets

1 Reverse Output

In a typical problem solving in the stack are good, there is a class has the following characteristics: First, although a clear algorithm, but the answer was given in the form of a linear sequence; secondly, whether recursive or iterative implementation, the sequence is calculated according to the reverse order book to eat. Finally, the size of the input and output uncertain, difficult to determine the size of the container in full bloom output data. Because of its unique "last in, first out" characteristics and adaptability in terms of capacity, the stack can be used to solve such problems.

Base conversion:

Given any decimal integer n, which is converted to binary representation of λ.

void Convert (Stack < char > _int64 & S n,, int  base ) { // positive decimal numbers to the base n-ary conversion (recursive version) 
    static  char digit for [] = { ' 0 ' , ' . 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , 'A', ' B ' , ' C ' , ' D ' , ' E ' , ' F. ' }; // digit binary symbols in the new 
    IF ( 0 < n-) { 
        S.puch (digit for [n- % Base ]); // reverse current lowest bit recording, and then all of the lowest level by recursively obtained 
        Convert (S, n-/ Base , Base ); 
    } 
} // each digit hexadecimal descending under the new, top-down stack S stored in in

Simply high to low which sequentially outputs to the stack through repeated operations after calculation.

void Convert (Stack < char > & _int64 S n,, int  base ) { // decimal base to n-ary conversion (iteration Edition)   
    static  char digit for [] = { ' 0 ' , ' . 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , 'A', ' B ' , ' C ' , ' D ' , ' E ' , ' F. ' };
     The while (n-> 0 ) { // high to low, the number of useful calculated for each new bit binary 
        int REMAINDER = ( int ) (n-% base ); 
        S.puch (digit for [rEMAINDER]); // remainder of the stack 
        n-/ = base ; // n-update its base in addition to the commercially 
    } 
}

 

Guess you like

Origin www.cnblogs.com/biwangwang/p/11332465.html