2
2
* Exercise 4-4. Add commands to print the top element of the stack without
3
3
* popping, to duplicate it, and to swap the top two elements. Add command to
4
4
* clear the stack.
5
+ *
5
6
* By Faisal Saadatmand
6
7
*/
7
8
13
14
#define NUMBER '0' /* signal that a number was found */
14
15
#define MAXVAL 100 /* max depth of val stack */
15
16
#define BUFSIZE 100
16
- #define TOP val[sp - 1] /* top element in stack */
17
17
18
18
/* functions */
19
19
int getop (char []);
@@ -31,7 +31,6 @@ int sp; /* next free stack position */
31
31
double val [MAXVAL ]; /* value stack */
32
32
char buf [BUFSIZE ]; /* buffer from ungetch */
33
33
int bufp ; /* next free position in buf */
34
- int peak ; /* flag to peak at top of the stack */
35
34
36
35
/* push: push f onto value stack */
37
36
void push (double f )
@@ -103,19 +102,18 @@ void ungetch(int c)
103
102
/* printTOP: print top of the stack without pop */
104
103
void printTOP (void )
105
104
{
106
- if (sp < 1 )
107
- printf ("stack empty\n" );
108
- printf ("\t%.8g\n" , TOP );
105
+ double top ;
106
+
107
+ top = pop ();
108
+ printf ("\t%.8g\n" , top );
109
+ push (top );
109
110
}
110
111
111
112
/* duplicateTop: duplicate the top element in the stack */
112
113
void duplicateTop (void )
113
114
{
114
115
double top ;
115
116
116
- if (sp < 1 )
117
- return ;
118
-
119
117
push (top = pop ());
120
118
push (top );
121
119
}
@@ -125,24 +123,12 @@ void duplicateTop(void)
125
123
{
126
124
double top1 , top2 ;
127
125
128
- if (sp < 2 ) {
129
- if (sp == 1 )
130
- printf ("error: 1 element in stack\n" );
131
- return ;
132
- }
133
126
top1 = pop ();
134
127
top2 = pop ();
135
128
push (top1 );
136
129
push (top2 );
137
130
}
138
131
139
- /* clear: clears the entire stack */
140
- void clearStack (void )
141
- {
142
- while (sp > 1 )
143
- pop ();
144
- }
145
-
146
132
/* reverse Polish Calculator */
147
133
int main (void )
148
134
{
@@ -179,24 +165,17 @@ int main(void)
179
165
else
180
166
printf ("error: zero divisor\n" );
181
167
break ;
182
- case '! ' :
183
- peak = 1 ;
168
+ case '? ' :
169
+ printTOP () ;
184
170
break ;
185
- case '# ' :
171
+ case 'd ' :
186
172
duplicateTop ();
187
173
break ;
188
- case '& ' :
174
+ case 's ' :
189
175
swapTopTwo ();
190
176
break ;
191
- case '~' :
192
- clearStack ();
193
- break ;
194
177
case '\n' :
195
- if (peak ) {
196
- printTOP ();
197
- peak = 0 ;
198
- } else
199
- printf ("\t%.8g\n" , pop ());
178
+ printf ("\t%.8g\n" , pop ());
200
179
break ;
201
180
default :
202
181
printf ("error: unknown command %s\n" , s );
0 commit comments