0% found this document useful (0 votes)
30 views2 pages

EOP C

The document contains a C program that implements a stack data structure to evaluate postfix expressions. It includes functions for stack operations such as push, pop, and peek, as well as a function to evaluate the postfix expression. The main function demonstrates the evaluation of a specific postfix expression, '231*+9-'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views2 pages

EOP C

The document contains a C program that implements a stack data structure to evaluate postfix expressions. It includes functions for stack operations such as push, pop, and peek, as well as a function to evaluate the postfix expression. The main function demonstrates the evaluation of a specific postfix expression, '231*+9-'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <ctype.

h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Stack {
int top;
unsigned capacity;
int* array;
};

struct Stack* createStack(unsigned capacity) {


struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
if (!stack)
return NULL;

stack->top = -1;
stack->capacity = capacity;
stack->array = (int*)malloc(stack->capacity * sizeof(int));

if (!stack->array)
return NULL;
return stack;
}

int isEmpty(struct Stack* stack) {


return stack->top == -1;
}

int peek(struct Stack* stack) {


return stack->array[stack->top];
}

int pop(struct Stack* stack) {


if (!isEmpty(stack))
return stack->array[stack->top--];
return -1; // Use -1 to indicate an error instead of '$'
}

void push(struct Stack* stack, int op) {


stack->array[++stack->top] = op;
}

int evaluatePostfix(char* exp) {


struct Stack* stack = createStack(strlen(exp));
int i;

if (!stack)
return -1;

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[] = "231*+9-";

printf("Postfix evaluation: %d\n", evaluatePostfix(exp));


return 0;
}

You might also like