-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment 8.cpp
More file actions
164 lines (160 loc) · 2.37 KB
/
Assignment 8.cpp
File metadata and controls
164 lines (160 loc) · 2.37 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//============================================================================
// Name : Assignment 8.cpp
// Author : 21258
// Version :
// Copyright : Your copyright notice
// Description : Expression conversion (infix to postfix) using stack
//============================================================================
#include <iostream>
#include<string.h>
using namespace std;
class node{
public:
char s;
node *next;
node()
{
s=' ';
next=NULL;
}
};
class Stack{
public:
node *top;
Stack()
{
top=NULL;
}
bool isempty()
{
if(top==NULL)
return 1;
else
return 0;
}
void push(char c)
{
if(!isempty())
{
node *t=new node();
t->s=c;
t->next=top;
top=t;
}
else
{
top=new node();
top->s=c;
}
}
void pop()
{
node *t=top;
top=top->next;
delete t;
}
};
string check(string r, int l)
{
Stack s2;
string n[10];
int j=0;
for(int i=0;i<l;i++)
{
if(r[i]=='+'||r[i]=='-'||r[i]=='*'||r[i]=='/')
{
if(s2.isempty())
s2.push(r[i]);
else
{
if((s2.top->s=='+'||s2.top->s=='-')&&(r[i]=='*'||r[i]=='/'))
s2.push(r[i]);
else
{
do
{
j=j-2;
n[j]=n[j]+n[j+1]+s2.top->s;
n[j+1]='\0';
s2.pop();
j=j+1;
if(s2.isempty())
break;
}
while((s2.top->s=='+'&&r[i]=='-')||(s2.top->s=='-'&&r[i]=='+'));
s2.push(r[i]);
}
}
}
else
{
n[j++]=r[i];
}
}
while(!s2.isempty())
{
n[j++]=s2.top->s;
s2.pop();
}
for(int i=0;i<l;i++)
cout<<n[i];
for(int i=1;i<l;i++)
{
n[0]+=n[i];
}
string t=n[0];
return t;
}
void eval(string r, int l)
{
Stack s;
int g=l/2+1,a[100],res=0,x,y;
cout<<"Enter the values of "<<g<<" operands in their order of appearance in the postfix form : "<<endl;
for(int i=0;i<g;i++)
cin>>a[i];
for(int i=0,j=0;i<l;i++)
{
if(r[i]=='+'||r[i]=='-'||r[i]=='*'||r[i]=='/')
{
x=s.top->s;
s.pop();
y=s.top->s;
s.pop();
}
switch(r[i])
{
case '+':
res=x+y;
s.push(res);
break;
case '*':
res=x*y;
s.push(res);
break;
case '-':
res=y-x;
s.push(res);
break;
case '/':
res=y/x;
s.push(res);
break;
default:
s.push(a[j++]);
}
}
cout<<res;
}
int main() {
Stack s;
string r,q;
int l;
cout<<"Enter the expression: ";
cin>>r;
l=r.length();
q=check(r,l);
cout<<endl;
int z=q.length();
eval(q,z);
return 0;
}