Skip to content

Commit

Permalink
Added Postfix To Infix in C and C++ (#992)
Browse files Browse the repository at this point in the history
  • Loading branch information
somya-kapoor authored and jainaman224 committed Apr 20, 2019
1 parent e6921ca commit e340b0f
Show file tree
Hide file tree
Showing 2 changed files with 130 additions and 0 deletions.
66 changes: 66 additions & 0 deletions Postfix_To_Infix/Postfix_To_Infix.c
@@ -0,0 +1,66 @@
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <stdbool.h>

char stack[20];
int top = -1;

//Pop the top value from the stack.
char pop()
{
return stack[top--];
}

//Push it onto the stack.
void push(char ch)
{
stack[++top] = ch;
}

//Checking if it is operator or letter
bool operand(char x)
{
if(x == '+' || x == '-' || x == '*'|| x == '/')
return true;
return false;
}

void postfix_to_infix(char postfix[])
{
int length;
char element, operator;
length = strlen(postfix);
printf("\nInfix Expression: ");
printf("%c", postfix[0]);
for(int count = 1; count < length; count++)
{
// If the character is not an operand.
if(!operand(postfix[count]))
{
//If the character is letter , push it in the stack
push(postfix[count]);
}
else
{
//pop the element present in the stack
element = pop();
//character is assigned to operator
operator = postfix[count];
printf(" %c %c", operator, element);
}
}
}

int main()
{
char postfix[20];
printf("Enter Postfix Expression: ");
scanf("%s", postfix);
postfix_to_infix(postfix);
return 0;
}

/*
Enter Postfix Expression: ab*c+
Infix Expression: a * b + c*/
64 changes: 64 additions & 0 deletions Postfix_To_Infix/Postfix_To_Infix.cpp
@@ -0,0 +1,64 @@
# include <iostream>
# include <cstring>
using namespace std;

char stack[20];
int top = -1;

//Pop the top value from the stack.
char pop()
{
return stack[top--];
}

//Push it onto the stack.
void push(char ch)
{
stack[++top] = ch;
}

//Checking if it is operator or letter
bool operand(char x)
{
if(x == '+' || x == '-' || x == '*'|| x == '/')
return true;
return false;
}

void postfix_to_infix(char postfix[])
{
int length;
char element,operators;
length = strlen(postfix);
cout << "\nInfix Expression: ";
cout << postfix[0];
for(int count = 1; count < length; count++)
{
// If the character is not an operand.
if(!operand(postfix[count]))
{
//If the character is letter , push it in the stack
push(postfix[count]);
}
else
{
//pop the element present in the stack
element = pop();
//character is assigned to operator
operators = postfix[count];
cout << operators << element ;
}
}
}

int main()
{
char postfix[20];
cout << "Enter Postfix Expression: ";
cin >> postfix;
postfix_to_infix(postfix);
return 0;
}

/*Enter Postfix Expression: ab*c+
Infix Expression: a*b+c */

0 comments on commit e340b0f

Please sign in to comment.