GATE / CS ARCHIVE

SIMILAR QUESTIONS / DATA STRUCTURES

Convert infix using precedence stack

2 questions solved the same way, newest first. Back to Data Structures

How these are solved

Scan infix tokens, stack operators/function applications, and emit postfix according to parentheses, stated precedence and associativity. Unary log and right-associative exponentiation are distinct operator constraints.

2 marks · MCQ
Report issue

Postfix with right-associative exponentiation

Stacks & Queues

Question 38, GATE 2004: Operators +,−,× are left-associative and ^ is right-associative. Precedence from highest to lowest is ^,×,+,−. Find postfix for a+b×c−d^e^f. Tokens in each alternative are separated for readability.
Options:
(A) a b c × + d e f ^ ^ −
(B) a b c × + d e ^ f ^ −
(C) a b + c × d − e ^ f ^
(D) − + a × b c ^ ^ d e f
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (13 steps)

1. The grouping is(a+(b×c))−(de^f). Write each subtree’s operands before its operator: a b c × + d e f ^ ^ −.

2. Thus A. Right associativity places the ef operation before raising d to that result.

3. Teaching check: The parse first builds b×c and ef, then de^f, then a+(b×c), and finally subtraction. Postorder traversal emits operands before operators. The alternative with d e ^ f ^ instead encodes (de)f and violates right associativity.

Original paper, page 5

Descriptive
Report issue

Postfix conversion

Stacks & Queues

Question 19(b), GATE 1998: Find postfix for 3*log(x+1)−a/2.
Question 19(b), GATE 1998: Find postfix for 3*log(x+1)−a/2.
Tap to enlarge
Answer & solution

Answer: 3 x 1 + log * a 2 / − (no official key was published)

Step through it (14 steps)

First parenthesize by the usual precedence and the unary function call: (3*log(x+1))−(a/2). A postfix traversal writes operands before their operator. The subtree x+1 becomes x 1 +; applying the unary log appends log, giving x 1 + log. Multiplication by 3 becomes 3 x 1 + log *. Independently, a/2 becomes a 2 /. Finally append subtraction after both subexpressions:

3 x 1 + log * a 2 / −

The spaces separate tokens, and log is one unary operator rather than three operands. Evaluating this stack form pushes 3, forms log(x+1), multiplies, forms a/2, then subtracts the right value from the left. Reversing the final operands would change the expression.

Original paper, page 7