Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Evaluate postfix expression using stack

Write an efficient algorithm to evaluate postfix expression using stack.

Evaluate the following postfix expression using stack.

Expression 138*+

Result : 25

Stack Areamaintop(pointer)postfix_expindex (int) =5opr_1 (int) =24opr_2 (int) =1status (int) =1temp(pointer)top(pointer) Heap Areaarray (char) [0] 1 [1] 3 [2] 8 [3] * [4] + [5] \0struct Stackdata (int)= 25next (pointer)= NULL

Code Visualize Try it Yourself

Another example:

Expression 231*+9-

Output -4

view process

Stack Areamaintop(pointer)postfix_expindex (int) =7opr_1 (int) =9opr_2 (int) =5status (int) =1temp(pointer)top(pointer) Heap Areaarray (char) [0] 2 [1] 3 [2] 1 [3] * [4] + [5] 9 [6] - [7] \0struct Stackdata (int)= -4next (pointer)= NULL

Code execution Try it Yourself

This function accept two parameters.

1) First index address of string

2) One stack double pointer

This function are perform two stack operation.

1) push : when operand are found

2) pop : when operator are found

Wap to evaluate postfix expression using stack in c. Time complexity O(n).


Output

Stack Areamaintop(pointer)postfix_expindex (int) =4opr_1 (int) =24opr_2 (int) =3status (int) =1temp(pointer)top(pointer)popremove(pointer)top(pointer) Heap Areaarray (char) [0] 1 [1] 3 [2] 8 [3] * [4] + [5] \0struct Stackdata (int)= 1next (pointer)= NULLstruct Stackdata (int)= 24next (pointer)

Execution Process Try it Yourself

Spread the post

Recommended Posts: