Update convert.c

added comments for better readability
This commit is contained in:
ashish4321 2017-09-19 10:44:51 +05:30 committed by GitHub
parent 6974f28d61
commit f361d45483

View File

@ -1,18 +1,22 @@
#include<stdio.h> //convert infix to postfix
char stack[20]; #include <stdio.h>
int top = -1; char stack[20]; //declaring an empty stack
void push(char x) int top = -1; //declaring top of stack
void push(char x) //push function
{ {
stack[++top] = x; stack[++top] = x; //each time it is pushed top is increamented
} }
char pop()
char pop() //pop function
{ {
if(top == -1) if(top == -1)
return -1; return -1;
else else
return stack[top--]; return stack[top--]; //each time it is popped top is decreamented
} }
int priority(char x)
int priority(char x) // to check the priority of characters
{ {
if(x == '(') if(x == '(')
return 0; return 0;
@ -35,23 +39,24 @@ int main()
{ {
if(isalnum(*e)) if(isalnum(*e))
printf("%c",*e); printf("%c",*e);
else if(*e == '(') else if(*e == '(') //push it directly into the stack
push(*e); push(*e);
else if(*e == ')') else if(*e == ')') //pop until we gwt the left parenthesis
{ {
while((x = pop()) != '(') while((x = pop()) != '(')
printf("%c", x); printf("%c", x);
} }
else else
{ {
while(priority(stack[top]) >= priority(*e)) while(priority(stack[top]) >= priority(*e)) //pop until priority of top of stack is greater than equal to priority of expressions character
printf("%c",pop()); printf("%c",pop());
push(*e); push(*e); //otherwise push
} }
e++; e++;
} }
// keep popping until top is not -1
while(top != -1) while(top != -1)
{ {
printf("%c",pop()); printf("%c",pop());
} }
} }