-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathpostfixToInfix.c
98 lines (88 loc) · 1.69 KB
/
postfixToInfix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//Tree declaration
struct Node
{
char c;
struct Node *left;
struct Node *right;
};
typedef struct Node node;
node* createnode(char data)
{
node* new_node = ((node*)malloc(sizeof(node)));
new_node->c=data;
new_node->left=new_node->right=NULL;
return new_node;
}
//stack declaration
node *stack[100];
int top=-1;
void push(node *temp){
if (top==100)
{
printf("Stack is full\n");
return;
}
stack[top+1]=temp;
top++;
}
void pop(){
if (top==-1)
{
printf("stack is empty.Nothing to pop.\n");
return;
}
top--;
}
// Postfix To Infix
int isOperator(char c){
if (c=='+' || c=='-' || c=='/' || c=='*' || c=='^')
return 1;
return 0;
}
node *toInfix(char postfix[]){
node *t,*t1,*t2;
for (int i = 0; i < strlen(postfix); i++)
{
if (!isOperator(postfix[i]))
{
t=createnode(postfix[i]);
push(t);
}
else
{
t=createnode(postfix[i]);
t1=stack[top];
pop();
t2=stack[top];
pop();
t->right=t1;
t->left=t2;
push(t);
}
}
//get root element
t=stack[top];
pop();
return t;
}
// Inorder Traversal
void inorder(node *root){
if (root==NULL)
return;
inorder(root->left);
printf("%c",root->c);
inorder(root->right);
}
// main
int main(){
char postfix[] = "ab+ef*g*-";
node *root = toInfix(postfix);
printf("\nPostfix expression is : %s",postfix);
printf("\nInfix expression is : ");
inorder(root);
printf("\n\n");
return 0;
}