Parenthesis checker not working

+2 pratt 15 · August 28, 2014
My parenthesis program in c using stacks is not working correctly......plz correct the error and let me know about the same.


#include<stdio.h>
#include<conio.h>

typedef struct{
char info;
struct stack* next;
}stack;
stack *top;

typedef enum{false,true}boolean;

boolean create_stack(stack **top){
top=NULL;
}

boolean isempty(stack **top){
if(top==NULL)
    return true;
else
    return false;
}

void push(stack **top,char data);
void display(stack **top);
void pop(stack **top);
int check(stack **top, char exp);


void  main(){
    int i,c;
    create_stack(&top);
    char exp[20]="[{}]";
    for(i=0;i<20;i++){
        if(exp=='{'||exp=='('||exp=='['){
            push(&top,exp);
            if(exp=='}'||exp==')'||exp==']'){
               c=check(&top,exp);
                if(c==1)
                    pop(&top);

            }
           }
    }
    if(isempty(&top))
        printf("Exp is correct");
        else
            printf("Exp is incorrect");

            //display(&top);


}

void push(stack **top,char data){
stack *ptr;
ptr=(stack *) malloc(sizeof(stack));
ptr->info=data;
ptr->next=*top;
*top=ptr;
}

void display(stack **top){
    stack *ptr;
    ptr=*top;
while(ptr!=NULL){
    printf("element: %d \n",ptr->info);
    *top=(*top)->next;
    ptr=*top;
}
}

void pop(stack **top){
while(*top=NULL){
    stack *ptr;
    ptr=(stack *) malloc(sizeof(stack));
    ptr=top;
    *top=(*top)->next;
    free(ptr);

}
}

int check(stack **top, char exp){
        if(*top=='{' && exp=='}')
            return 1;
           else if(*top=='(' && exp==')')
            return 1;
             else if(*top=='[' && exp==']')
            return 1;
             else
            return 0;

}

Post a Reply

Replies

Oldest  Newest  Rating
+2 Mathias Frits Rørvik · August 29, 2014

while(*top=NULL){



This line is wrong, it should probably be != NULL?
0 Yujin D. Great · August 31, 2014
I think the problem is inside the for loop.

try doing this.


if(exp=='{'||exp=='('||exp=='['){
push(&top,exp);
if(exp=='}'||exp==')'||exp==']'){
c=check(&top,exp);
if(c==1)
pop(&top);
  • 1

C

107,313 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator