-
Notifications
You must be signed in to change notification settings - Fork 0
/
Infix to Postfix using Stacks
101 lines (87 loc) · 1.39 KB
/
Infix to Postfix using Stacks
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
99
100
101
#include<bits/stdc++.h>
using namespace std;
struct Node
{
char data;
struct Node *next;
}*top=NULL;
void push(char x)
{
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
t->data=x;
t->next=top;
top=t;
}
int pop()
{
int x=-1;
struct Node *t;
if (top==NULL)
printf("Stack is Empty");
else
{
t=top;
x=t->data;
top=t->next;
free(t);
}
return x;
}
int isOperand(char ch)
{
if(ch=='*'||ch=='/'||ch=='+'||ch=='-')
return 0;
else
return 1;
}
int pre(char ch)
{
if(ch=='*'||ch=='/')
return 2;
else
return 1;
}
void Display()
{
struct Node *p;
p=top;
while(p!=NULL)
{
cout<<p->data;
p=p->next;
}
}
int main()
{
cout<<"Enter Expression";
string str;
cin>>str;
struct Node *t;int k=0;int i=0;int j=0;
char str1[1000];
while(str[i]!='\0')
{
if(isOperand(str[i]))
{
str1[j++]=str[i++];
} else
{
if(top==NULL)
push(str[i++]);
else
{
if(pre(str[i])<=pre(top->data))
str1[j++]=pop();
else
{
push(str[i++]);
}
}
}
}
while(top!=NULL)
{
str1[j++]=pop();
}
cout<<str1;
}