Created
August 9, 2018 15:32
-
-
Save amithkk/53d031a53d564ecc68fee66f2264f85a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
3.Write a C program to convert and print a given valid parenthesized infix arithmetic expression to postfix expression. | |
The expression consists of single character and binary operators + - * /. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
#define STKSZ 100 | |
struct stack { char items[STKSZ]; int top} stk; | |
void push(char ele) | |
{ | |
if (stk.top + 1 == STKSZ) { | |
printf("\n[E] Stack Overflow!\n"); | |
exit(1); | |
} | |
stk.items[++stk.top] = ele; | |
} | |
char pop() | |
{ | |
if (stk.top == -1) { | |
printf("\n[E] Stack Underflow!\n"); | |
exit(1); | |
} | |
return (stk.items[stk.top--]); | |
} | |
int priority(char c) | |
{ | |
switch (c) | |
{ | |
case '(': return 0; | |
case '+': case '-': return 1; | |
case '*': case '/': return 2; | |
case '$': return 3; | |
} | |
} | |
int main() | |
{ | |
char expr[100], *e, x; | |
printf("Enter Infix Expression:"); | |
scanf("%s", expr); | |
printf("Postfix Expression:"); | |
stk.top = -1; | |
for (e = expr; *e != '\0'; e++) | |
{ | |
if (isalnum(*e)) | |
printf("%c", *e); | |
else if (*e == ')') | |
{ | |
while ( (x = pop()) != '(') | |
printf("%c", x); | |
} | |
else if (*e == '(') | |
push(*e); | |
else | |
{ | |
while ( priority(stk.items[stk.top]) >= priority(*e) ) | |
printf("%c", pop()); | |
push(*e); | |
} | |
} | |
while (stk.top != -1) | |
printf("%c", pop()); | |
putchar('\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment