Another stack problem.
Now this is not my code. HINT: This one actually works. (ha ha)
I would like to change from using all functions that pass pointers to having only the PUSH function passing a value. Would this work?? And I think I want the functions to match my stack functions from my original STACK program. (which still ain't working -- but will be soon)
Oh, and I would like there to be a better confirmation output instead of just "Correct" when the program finds that the brackets, and braces and parentheses all are balanced for whatever expression is input.
ex. input : {6*5 [y*5] / (a*8)}
output : your expression has balanced symbols
or something like that. What seems like a good output so user knows they input a correct looking expression ??
Also, my instructor said something about using the ASCII codes for the r/l brackets, braces and parentheses. If I did that, would I have to write something like:
instead of
Code:
while (a[i] != NULL)
{if (a[i] == '(')
push (&top, '(');
if (a[i] == ')')
{ if (is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
pop (&top);
}
i++;
}
write this
Code:
while (a[i] != NULL)
{if (a[i] == '\40' ) /* \40 is the character ( */
push (&top, '\40');
if (a[i] == '\41' ) /* \41 is the character ) */
{ if (is_empty(&top))
printf("Incorrect\n");
exit(0);
}
pop (&top);
}
i++;
}
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
typedef struct {
char sa[N];
int count;
}Stack;
void intialize (Stack *);
int is_empty (Stack *);
void push (Stack *, char);
char pop (Stack *);
void cleara(Stack *, int);
int main ()
{
int i = 0;
char a[N];
Stack top;
printf("Please enter a string to be evaluated: ");
gets(a);
intialize (&top);
while (a[i] != NULL)
{if (a[i] == '(')
push (&top, '(');
if (a[i] == ')')
{ if (is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
pop (&top);
}
i++;
}
if (!is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
cleara(&top, N);
i=0;
while (a[i] != NULL)
{if (a[i] == '[')
push (&top, '[');
else
if (a[i] == ']')
{ if (is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
pop (&top);
}
i++;
}
if (!is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
cleara(&top, N);
i=0;
while (a[i] != NULL)
{if (a[i] == '{')
push (&top, '{');
if (a[i] == '}')
{ if (is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
pop (&top);
}
i++;
}
if (!is_empty(&top))
{printf("Incorrect\n");
exit(0);
}
printf("Correct\n");
return 0;
}
void intialize (Stack *ptop)
{
ptop->count = 0;
}
int is_empty (Stack *ptop)
{
if (ptop->count == 0)
return 1;
return 0;
}
void push (Stack *ptop, char p)
{
ptop->sa[ptop->count] = p;
(ptop->count)++;
}
char pop (Stack *ptop)
{
char temp;
temp = ptop->sa[ptop->count-1];
(ptop->count)--;
return temp;
}
void cleara(Stack *ptop, int n)
{ int i;
for (i=0; i<n; i++)
ptop->sa[i] = '\0';
}