SCENARIO BASED SIDHARTH K
RA2011003010008
CSE A1
Question:
Given string S representing a postfix expression, the task is to evaluate the expression and
find the final value.
Approach:
Input is put into stack and each character is evaluated with switch case.
Scalability:
User inputs the desired data.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
//declaring structure stack
struct Stack
{
int top;
int size;
int *array;
};
//Create stack
struct Stack *createStack(int size)
{
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->size = size;
stack->array = (int *)malloc(stack->size * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
//Checks if stack is empty
int isEmpty(struct Stack *stack)
{
return stack->top == -1;
}
//returns top value
char peek(struct Stack *stack)
{
return stack->array[stack->top];
}
//function to remove an element from stack
char pop(struct Stack *stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--];
return '$';
}
//function to insert elements into stack
void push(struct Stack *stack, char op)
{
stack->array[++stack->top] = op;
}
// Evaluates postfix expression
int evaluatePostfixExpression(char *exp)
{
struct Stack *stack = createStack(strlen(exp));
int i;
// See if stack was created successfully
if (!stack)
return -1;
// Scans all characters one by one
for (i = 0; exp[i]; ++i)
{
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+':
push(stack, val2 + val1);
break;
case '-':
push(stack, val2 - val1);
break;
case '*':
push(stack, val2 * val1);
break;
case '/':
push(stack, val2 / val1);
break;
}
}
}
return pop(stack);
}
int main()
{
char exp[10];
int n;
printf("Enter Total Test Cases\n");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%s", exp);
printf("EXPRESSION IN POSTFIX: %d\n", evaluatePostfixExpression(exp));
}
return 0;
}
Sample input output:
Dryrun:
Time and space complexity:
Time Complexity: O(n)
Space Complexity: O(1)