From a566c2ace9af491ecb2f5ac4d429ac50a8d53e1a Mon Sep 17 00:00:00 2001 From: anand-aman <54910807+anand-aman@users.noreply.github.com> Date: Thu, 19 Dec 2019 01:55:28 +0530 Subject: [PATCH] Issue #159 Infix to Postfix Expression using Stack in C language #159 --- InfixToPostfix.c | 73 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 InfixToPostfix.c diff --git a/InfixToPostfix.c b/InfixToPostfix.c new file mode 100644 index 0000000..79adf04 --- /dev/null +++ b/InfixToPostfix.c @@ -0,0 +1,73 @@ +#include +#include +#include + +char stack[50]; +int top=-1; + +void push(char ch) +{ + stack[++top]=ch; +} + +int pop(){ + return(stack[top--]); +} + +int prior(char ch) +{ + int p; + + if(ch=='#' || ch=='(') + p=1; + if(ch=='+' || ch=='-') + p=2; + if(ch=='*' || ch=='/') + p=3; + if(ch=='$' || ch=='^') + p=4; + + return p; +} + +int main() +{ + char infix[100], postfix[100]; + int i=0,j=0; + + printf("Enter infix expression: "); + scanf("%s",infix); + + push('#'); + + for (int i = 0; i < strlen(infix); i++) + { + if(isalnum(infix[i])) + postfix[j++]=infix[i]; + + else if(infix[i] == '(') + push(infix[i]); + + else if(infix[i]==')') + { + while(stack[top]!='(') + postfix[j++] = pop(); + pop(); + } + + else + { + while(prior(stack[top])>=prior(infix[i])) + postfix[j++]=pop(); + push(infix[i]); + } + } + + while(stack[top]!='#') + postfix[j++]=pop(); + postfix[j]='\0'; + + printf("Postfix expression: "); + printf("%s\n",postfix); + return 0; +}