Hello to you all ,

I am required to write a program which gets a Math Expression (without checking it is good) and put in Stack only the Brackets .
Implementation of Stack is One-Way Linked List Only.

Examples for Good/Bad Expressions :
(a*{b+c}-4/x +[e-5]) - GOOD
(5+} - BAD
(5+{6*)-2} - BAD
(5+z - BAD

I have build up a Mechanism which checks for each entered char (other than Enter Key and also using closing brackets such as ) or ] or } at the beginning of Expression) what type of bracket it is and pushes it into a stack (we must use LIFO technique for check legal Expression).

I thought of 2 cases :

first case : for each open bracket there is a closing one so i check top of stack to bottom of stack and carry on till i reach to middle .
second case : what happens if i have this sequence - ()[]{} - meaning i need to check top against the next , and so on (top of stack to bottom of stack will not help in this case)

I kinda stuck on Algorithm Think Phase :-)

Code Added . Any Ideas ?

Thank you , Yotam , Israel

Attachments
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Node
{	char data;
	struct Node *next;
}node;

void push(char);
void display_stack();

node  *top;

int  main()
{
 char temp[80];
 int i=0,counter=0;
 clrscr();
 printf("\nEnter Math Expression\n");
 top=NULL;
 temp[i]=getche();
 if ( (temp[i]==')') || (temp[i]==']') || (temp[i]=='}') )
    { printf("\n Bad Expression! Run it Again... \n"); getch(); return 1; }
 else
  {
  while ( (int)temp[i]!=13 )
    {

    switch (temp[i])
       {
       case '(': { push(temp[i]); counter++; break; }
       case ')': { push(temp[i]); counter++; break; }
       case '[': { push(temp[i]); counter++; break; }
       case ']': { push(temp[i]); counter++; break; }
       case '{': { push(temp[i]); counter++; break; }
       case '}': { push(temp[i]); counter++; break; }
       }
     ++i;
     temp[i]=getche();
     }
  }

if ( (counter%2)!=0 ) printf("Bad Expression! \n");
else { display_stack(); }

return 0;
}


void push(char y)
{
	node *ptr;
	ptr=malloc(sizeof(node));
	ptr->data = y;
	ptr->next = top;
	top = ptr;
}

void display_stack()
 {
 int i =0;
 node * temp;
 temp = top;
 while(temp!=NULL)
  {
  printf("\nNode #%2d  :  Value= %c    next %5x ",i++,temp->data,temp->next);
  temp=temp->next;
  }
 }

/* REMOVES TOP NODE FROM  THE STACK AND RETURNS ITS VALUE*/

int pop()
{
  char a;
  if(top==NULL)
     { printf("\n\t\tSTACK EMPTY...\n\n"); return 0; }
  else
    {
    a=top->data;
    printf("\n\n\nB4 pop: value 2B returned : %c ",a);
    free(top);
    top=top->next;
    return a;
    }
}
The logic should be like this :
   while ( input != 13 )
      {
       if input is '(' or '{' or '[' or ')' or '}' or ']' 
          {
          if input is '(' or '{' or '['
              push it into the stack.
          else if input is  ')' or '}' or ']' 
              {
              if stack is empty
                       report error.
              pop cell from stack
              if cell "matches input" 
                       we are ok.
              else if cell dont "matches input" or stack is empty 
                       report error.
              }
          }
      }
   if  the stack is not empty
        report error.

Also I would suggest replacing your input function
with fgets.
A nice touch would be to add to the switch statment
a default case, checking if it is a number of math experssion.
Don't ever write code like this :

free(top);
    top=top->next;

Once you free(p), dont access it !!!!!!!!!!
It will probaly work, but its wrong, and
also your grade will be like it.

The logic should be like this :
   while ( input != 13 )
      {
       if input is '(' or '{' or '[' or ')' or '}' or ']' 
          {
          if input is '(' or '{' or '['
              push it into the stack.
          else if input is  ')' or '}' or ']' 
              {
              if stack is empty
                       report error.
              pop cell from stack
              if cell "matches input" 
                       we are ok.
              else if cell dont "matches input" or stack is empty 
                       report error.
              }
          }
      }
   if  the stack is not empty
        report error.

Also I would suggest replacing your input function
with fgets.
A nice touch would be to add to the switch statment
a default case, checking if it is a number of math experssion.
Don't ever write code like this :

free(top);
    top=top->next;

Once you free(p), dont access it !!!!!!!!!!
It will probaly work, but its wrong, and
also your grade will be like it.

I see your point :-)
i build something , but for some reason , it will state all Expression are OK and i tried to Debug it , and i cant figure what went wrong... Code Added . The check is though ASCII code :
'(' - ')' = 1
'' = 2
'{' - '}' = 2

Thanx

Attachments
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Node
{	char data;
	struct Node *next;
}node;

void push(char);
void display_stack();

node  *top;

int  main()
{
 char temp[80];
 int i=0,flag=1;

 clrscr();
 printf("\nEnter Math Expression\n");
 top=NULL;
 temp[i]=getche();
 if ( (temp[i]==')') || (temp[i]==']') || (temp[i]=='}') )
    { printf("\n Bad Expression! Run it Again... \n"); getch(); return 1; }
 else
  {
  while ( (int)temp[i]!=13 && (flag==1))
    {

    switch (temp[i])
       {
       case '(': { push(temp[i]);  break; }
       case '[': { push(temp[i]);  break; }
       case '{': { push(temp[i]);  break; }
       case ')': { flag=check(temp[i]);  }
       case ']': { flag=check(temp[i]);  }
       case '}': { flag=check(temp[i]);  }
       }
     i+=1;
     temp[i]=getche();
     }

  }
if (flag==1) printf("\nOK\n");
   else printf("\nNO!\n");

return 0;
}


void push(char y)
{
	node *ptr;
	ptr=malloc(sizeof(node));
	ptr->data = y;
	ptr->next = top;
	top = ptr;
}

void display_stack()
 {
 int i =0;
 node * temp;
 temp = top;
 while(temp!=NULL)
  {
  printf("\nNode #%2d  :  Value= %c    next %5x ",i++,temp->data,temp->next);
  temp=temp->next;
  }
 }

/* REMOVES TOP NODE FROM  THE STACK AND RETURNS ITS VALUE*/

char pop()
{
  char a;
  if(top==NULL)
     {/* printf("\n\t\tSTACK EMPTY...\n\n");*/ return 0; }
  else
    {
    a=top->data;
    // printf("\n\n\nB4 pop: value 2B returned : %c ",a);
    free(top);
    top=top->next;
    return a;
    }
}

int check(char x)
{
   char tmp;
   tmp = pop();
   switch (tmp)
   {
    case ')': { if( tmp-x!=1 ) return 0; break;}
    case ']': { if( tmp-x!=2 ) return 0; break;}
    case '}': { if( tmp-x!=2 ) return 0; break;}
   }
   return 1;
}

I already told you. Dont do this :

free(top);
    top=top->next;

Its very wrong !!!!!
And still you do it again !!!!
:mad:


First thing better change input by getche to fgets.


Do you think that this is nessary ???
if ( (temp==')') || (temp==']') || (temp=='}') )
{ printf("\n Bad Expression! Run it Again... \n");

add to

case ')': { flag=check(temp[i]);  }
       case ']': { flag=check(temp[i]);  }
       case '}': { flag=check(temp[i]);  }

break statemnts!


If the stack is not empty thats wrong

if ( top )
   {
   printf("Items on the stack\n");
   flag = 0;
   }

You are ignoring the case which pop returns zero.


last thing
'(' - ')' == -1

I already told you. Dont do this :

free(top);
    top=top->next;

Its very wrong !!!!!
And still you do it again !!!!
:mad:


First thing better change input by getche to fgets.


Do you think that this is nessary ???
if ( (temp==')') || (temp==']') || (temp=='}') )
{ printf("\n Bad Expression! Run it Again... \n");

add to

case ')': { flag=check(temp[i]);  }
       case ']': { flag=check(temp[i]);  }
       case '}': { flag=check(temp[i]);  }

break statemnts!


If the stack is not empty thats wrong

if ( top )
   {
   printf("Items on the stack\n");
   flag = 0;
   }

You are ignoring the case which pop returns zero.


last thing
'(' - ')' == -1

A few things :
1. how do you Take off the Top each time if not in that way?
2. Added Break Statements , still causes problems in Expression check ,
each EXP check gets OK ....
3. the If sentence - no Math Exp. starts with backwoards brackets. :-)
4. should i pass into the POP function a Pointer to FLAG ?

Thanx

The proramme was good..n i think output will be perfect..but i am in 3rd semester...it is a little bitdifficult for me to understand..is there any simpler code for this bracket checker.....?????

Hello to you all ,

I am required to write a program which gets a Math Expression (without checking it is good) and put in Stack only the Brackets .
Implementation of Stack is One-Way Linked List Only.

Examples for Good/Bad Expressions :
(a*{b+c}-4/x +[e-5]) - GOOD
(5+} - BAD
(5+{6*)-2} - BAD
(5+z - BAD

I have build up a Mechanism which checks for each entered char (other than Enter Key and also using closing brackets such as ) or ] or } at the beginning of Expression) what type of bracket it is and pushes it into a stack (we must use LIFO technique for check legal Expression).

I thought of 2 cases :

first case : for each open bracket there is a closing one so i check top of stack to bottom of stack and carry on till i reach to middle .
second case : what happens if i have this sequence - ()[]{} - meaning i need to check top against the next , and so on (top of stack to bottom of stack will not help in this case)

I kinda stuck on Algorithm Think Phase :-)

Code Added . Any Ideas ?

Thank you , Yotam , Israel

Comments
givemetehcodez, lazy

write a c++ program that reads from the user a mathematical expression like:
(3+(4-9) * (3/4) * (3+2))

1. your program should check if the expression is correct
1.1 An expression is correct if:
the parantheses are correctly added and are balanced
examples of not correct expressions can be:
)9+8(
(((8-1)

etc

Assume that the numbers are only one digit ( you can extend your program to read more than one digit numbers as a bonus)

2. If the expression is correct, your program should evaluate the expression and display the result.

hint ( use stacks ( certain types of linked lists ) to solve the problem.

Comments
givemetehcodez, lazy - thursday huh? you're screwed unless you start now
This article has been dead for over six months. Start a new discussion instead.