vendredi 14 août 2015

Balanced Expression

Below is the code to determine balancing of symbol.

If the expression is balanced then print appropriate message

E.g. ((A+B))+(C+D)) --> Balanced

((A+B)+(C+D) ---> Unbalanced

((A+B)+(C+D}) --> Unbalanced

Here is the code

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

struct Stack{
char data;
struct Stack *next;
};

void push(struct Stack **top,char data)
{
        struct Stack *new_node;
        if(*top==NULL)
        {
                new_node=malloc(sizeof(struct Stack));
                new_node->data=data;
                new_node->next=*top;
                *top=new_node;
        }
        else
        {
                new_node=malloc(sizeof(struct Stack));
                new_node->data=data;
                new_node->next=*top;
                *top=new_node;
        }
}
char pop(struct Stack **top,int flag)
{
        if(*top!=NULL && flag==0)
        {
                printf("\n Expression is In-Valid  :) \n");
                return '\0';
        }
        if(*top==NULL && flag ==1)
        {
                printf("\n Unbalanced Expression \n");
                return '\0';
        }
        if(*top!=NULL && flag==1)
        {
                struct Stack *temp=*top;
                char op;
                op=(*top)->data;
                *top=(*top)->next;
                free(temp);
                return op;
        }
}
/*void display(struct Stack *top)
{
        struct Stack *temp=top;
        while(temp)
        {
                printf("\n %c",temp->data);
                temp=temp->next;
        }
} */
int main(void)
{
        struct Stack *top=NULL;
        int i=0;
        char str[]="((A+B)+[C+D])",op;
        printf("\n Running the programe to check if the string is balanced or not ");
        for(i=0;str[i]!='\0';++i)
        {
                if(str[i]=='('||str[i]=='['||str[i]=='{'||str[i]=='<')
                        push(&top,str[i]);
                else if(str[i]==')'||str[i]==']'||str[i]=='}'||str[i]=='>')
                {
                        op=pop(&top,1);
                        if( (op=='('&&str[i]==')') || (op=='['&&str[i]==']') || (op=='{'&&str[i]=='}') || (op=='<'&&str[i]=='>'))
                        {
                                continue;
                        }
                        else
                        {
                                printf("\n The expression is un-balanced \n");
                                break;
                        }

                }

        }
        pop(&top,0);
        return 0;
}

But it does not give the desirable output. I have debuged the code but not able to find the issue

Can u please help and look into it ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire