Está en la página 1de 4
fQueves 167 is removed and again three quadruples replace it, leaving top four elements is removed from the stack, it causes a disk to be following sequence: pole 1 to pole 3, pole | to pole 2. pole 3 to pole pole 3. The stack now contains (2, 2, 1, 3)| uple is removed and three quadruples replace it, leaving these elements is removed from the stack, causing disks to be moved as = pole 2 to pole 1, pole 2 to pole 3, pole | to pole 3. All three disks are order on pole 3 as desjfed. The stack has precisely captured the essence of cursive algorithm, and Arithmetic Expressions. The problem of evaluating an’ arith- expression arises at all levels of computation, from hand calculations to = a pocket calculator to programming large computers. It is a nontrivial task sansform the expression into a sequence of simple arithmetic operations. In section we examine two important algorithms for such manipulations of etic expressions; both algorithms center around the use of stacks. In a se, however, this material could fall under the previous heading of “stacks and srsion,” since it is possible to view these algorithms as iterative implementa- as of their recursive counterparts (see Exercises 6 and 8). Before constructing algorithms for any task, we must have a clear under- ading of what the task is. For the evaluation of arithmetic expressions, what ‘se want to do is fairly obvious, except for one thing: given the arithmetic expression 4 + BC, we want to compute A + (B*C) and not (A + B)*C. Without parentheses, how do we know which one we want? The answer lies in she notion of precedence. It is the convention that the multiplicative operations of 169 multiplication and division take precedence over the additive operil addition and subtraction; in other words, when there are no parentheses § it otherwise, the multiplicative operations are done first, before the operations. All right, but how do we evaluate A — B + C? Should it be of evaluation is as follows: ACE AOC DS Eh ee eee + C) or (A — B) + C? Of course we want (A — B) + C, because If A+B convention that operations of equal precedence are performed from left (d ——— As a further example, 4/B*C would be evaluated as (A/B)+C Ga 2 A/(BxC). —-__—_ Our problem is thus to evaluate arithmetic expressions that contulll (C—D)*E ables, +, —, *, /, and parentheses, with the conventions that * and he ee done before + and — (in the absence of parentheses, of course!) ali) (C—D)*E+F sequences of +s and —s or sequencts of *s and /s will be done from | ea right. This evaluation is tricky and can be done by a very clever fue algorithm (see Exercise 6), but here we will do it by a simpler two-stage fl that emphasizes the use of stacks, We will first show how to evalual expression, assuming it has been converted into an intermediate form, und show how to do the conversion to that form. The intermediate form is Polish postfix notation, in which the of foliows its two operands, rather than separating them as in conventional nol For example, instead of A + B we would write AB + . (To eliminate the af ities possible when multicharacter variable names are adjacent to one anotly will insist that all variable names be single characters; this restriction is @ overcome by using separator characters, but at the expense of some cli presentation.) For A + B«C we would have ABC* +, which is interpra follows: The perands for the * are the B and\© that precede it; 1 operands of the + are A and the expression BC*. If instead we want (4 + we write AB + C+, so that the two operands for the + are the A and precede it, while the two operands for the * are the expression AB + and examples ABC = + and AB + C» illustrate the most important charactefl Polish postfix notation: it does not need parentheses or precedence con to indicate the order of the computation; the order is defined completely relative order of the operands and the operators. We can define the class of Polish postfix expressions recursively as {| such an expression is either a simple variable, or consists of two Polish expressions followed by an operator. The recursive definition gives us the the evaluation of postfix expressions. Consider, for example, the expressiai} (At B)x(C > D)*E + FY hat whenever we find two operands by an operator, that operator is applied to those operands En eee the substring consisting of the operands and Cat arg Fi ae ample, we replaced the substring “AB +” by the; value nod re ed the substring “CD ~” by the value of C ~ D: then we te aie consisting of the value of C — D followed by Ee a Hi oe ¢ +E, and so on, finally replacing the entire string with the a(C— D)*E+ F), ¢ precisely, the algori 2 the expression one character at a time ‘a stack and operators are applied to the u d replaced by the result of the operation. ementation of this Hae assuming 1}, Pi2],---»P La) he ie ie ee . ee of converting the usual infix ae pe 2 i Polish postfix form. To convert an expression into post atedly replace an operand-operator-operand sequence by operand-oper- eral rule used in this example is t ithm to evaluate postfix expressions operates by from left to right. Operands are op two stack entries, which are Algorithm 4.7 is a straightfor- that the postfix expression 1s : empty stack =| ton do “if P[i] is an operand then S = P[é) else we xeS S «value of the operator P{i) applied to x and y AB+CD-ExF+«, which corresponds to the expression’ ae ae : rithm 4.7 : Ne iat Cag 2k juation of Polish Pin} cks and Queues PREC as given in Table 4.1 to determine the relative in 3 ts. Notice that the “(” has precedence lower than the s. Ni ¢ and-operator. For example, the following illustrates the transformation af "precedence functio neces of iwo operato: iti 5 stack al ue aes ne #) ic operations in order to keep it in the stack ap) 5 é ‘ ky Jee DOeTx font oo ; [bottom of stack marker] (44 B)<((O 5D) 4g + Fy 0 {output string cursor] 0 [input string cursor], ee i arker} i cedence is set So fis is the end of input string marker; its preces Esl AB+ oe that it will cause the stack to be ee beh e ‘acter of inpul See ict+l {process next character of Bret case Eli) is an operand: AB+CD-—EsF++ [transfer it to the output string] i -j+l To do this as we scan the xpression from left to right, We tise x! siack as fol Be — Eli) if ea , e1 ? e fas ‘alte i i ack leit parel When we scan an operator, then we k its left operand has already Eli": $< El) Z [sacl u : nverted to postfix and is in the output 8. So, we store the operator @ stack and process its tight operand. Afte: hing with its right operan ae ? faa stack contents down to the matching par i Operator will conveniently be at the top of the stack; we remove it oe the output string. while x #“(" do Tt is clear from this description of the process that oper. joitl 4 into the output string and Operators go into the stack. However, if we hae Pijl-x finished the second of the two operands of an operator, then that operator StS oh on top of the stack and we must recognize that it is time to put if into the string. The end of the second of the Operands. occurs for some operiti closing parenthesis, at another operator for which the preceding was { operand, or at the end of the input string. The case of another opel handled by observing that, if this incoming operator has lower or equal dence to the one on top of the stack, then we must have completed the ich t) operand of the operator on top of the stack: tha a 2 ¢ / Pijj

También podría gustarte