Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

valid Parenthese using stack in c

I was solving the problem 20. Valid Parentheses in Leetcode using c and when they check this input s ="{[]}" the code returns false instead of true but I don’t see any problem with the code:

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

int isEmpty(stack p){
    return p ==NULL;
}

void push(stack *p,char x){
    node *new = (node*)malloc(sizeof(node));
    new->data = x;
    new->next = *p;
    *p = new;
}

void pop(stack *p){
    node *t=*p;
    *p=(*p)->next;
    free(t);
}
bool isValid(char* s) {
    stack p;
    if(s[1] == '\0') return false;

    for(int i=0;s[i]!= '\0';++i){
        if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
            push(&p,s[i]);
        }
        else{
            if((s[i]==')' && p->data == '(')||(s[i]==']' && p->data == '[') || (s[i]=='}' && p->data == '{'))
                pop(&p);
            else return false;
        }
    }
    return isEmpty(p);
}

I really don’t see any problem with the code, if you have any suggestion please help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The function isValid has undefined behavior (it is isInValid:)).

For starters the pointer p is not initialized and has an indeterminate value

stack p;

Secondly, consider for example string "]". For such a string the control will be passed to the if statement

 if((s[i]==')' && p->data == '(')||(s[i]==']' && p->data == '[') || (s[i]=='}' && p->data == '{'))

So even if the pointer p will be initialized as a null pointer expressions like that p->data are trying to access memory using a null pointer.

Also such a typedef declaration

typedef node* stack;

Where the pointer type is hidden will only confuse readers of the code.

Pay attention to that in the page your provided a reference to the function is declared like

bool isValid( const char* s)
              ^^^^^

because the passed string is not being changed within the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading