Hello.. I was trying this simple problem https://leetcode.com/problems/valid-parentheses/
I worte the code in C langauge but the code failed to pass a test case {[]}.
Here is my attached code. I would be grateful for the help.
struct Stack
{
char data;
struct Stack *next;
}*top = 0;
void push(char x)
{
struct Stack *t;
t = (struct Stack *)malloc(sizeof(struct Stack));
if(t==0)
return;
else
{
t->data = x;
t->next = top;
top = t;
}
}
char pop()
{
struct Stack *t;
char x=-1;
if(top==0)
return x;
else
{
t = top;
top = top->next;
x = t->data;
free(t);
return x;
}
}
char isTop()
{
char x = -1;
if(top==0)
return x;
return top->data;
}
bool isValid(char * exp){
for(int i=0;exp[i]!='\0';i++)
{
if(exp[i]=='{'||exp[i]=='('||exp[i]=='[')
push(exp[i]);
else if((exp[i]==')' && isTop()!='(') ||
(exp[i]=='}'&& isTop()!='{') ||
(exp[i]==']'&& isTop()!='['))
return false;
else if(exp[i]==')' || exp[i]==']' || exp[i]=='}')
{
if(top==0) // stack is empty..
return false;
pop();
}
}
if(top==0)
return true;
return false;
}