mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 23:09:36 +03:00
Update balanced parenthesis using stack in C
This commit is contained in:
parent
63412ed20f
commit
6c3d167c6d
@ -8,15 +8,15 @@ struct node
|
|||||||
char data;
|
char data;
|
||||||
struct node* link;
|
struct node* link;
|
||||||
};
|
};
|
||||||
int c=0;
|
int c=0; // c used as counter to check if stack is empty or not
|
||||||
struct node * head;
|
struct node * head; //declaring head pointer globally assigned to NULL
|
||||||
|
|
||||||
void push(char x)
|
void push(char x) //function for pushing
|
||||||
{
|
{
|
||||||
struct node*p,*temp;
|
struct node *p,*temp;
|
||||||
temp=(struct node*)malloc(sizeof(struct node));
|
temp=(struct node*)malloc(sizeof(struct node));
|
||||||
temp->data=x;
|
temp->data=x;
|
||||||
if(head==NULL)
|
if(head==NULL) //will be execute only one time i.e, 1st time push is called
|
||||||
{
|
{
|
||||||
head=temp;
|
head=temp;
|
||||||
p=head;
|
p=head;
|
||||||
@ -32,7 +32,7 @@ struct node*p,*temp;
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
char pop(void)
|
char pop(void) //function for pop
|
||||||
{
|
{
|
||||||
char x;
|
char x;
|
||||||
struct node*p=head;
|
struct node*p=head;
|
||||||
@ -44,15 +44,15 @@ char pop(void)
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int isBalanced(char *s) { //{[()]}
|
int isBalanced(char *s) {
|
||||||
int i=0;char x;
|
int i=0;char x;
|
||||||
while(s[i]!='\0')
|
while(s[i]!='\0') //loop for covering entire string of brackets
|
||||||
{
|
{
|
||||||
if(s[i]=='{'||s[i]=='('||s[i]=='[')
|
if(s[i]=='{'||s[i]=='('||s[i]=='[') //if opening bracket then push
|
||||||
push(s[i]);
|
push(s[i]);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if(c<=0)
|
if(c<=0) //i.e, stack is empty as only opening brackets are added to stack
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ int isBalanced(char *s) { //{[()]}
|
|||||||
return 0 ;
|
return 0 ;
|
||||||
}i++;
|
}i++;
|
||||||
}
|
}
|
||||||
if(c==0)
|
if(c==0) //at end if stack is empy which means whole process has been performed correctly so retuen 1
|
||||||
return 1;
|
return 1;
|
||||||
else
|
else
|
||||||
return 0;
|
return 0;
|
||||||
|
Loading…
Reference in New Issue
Block a user