Skip to content

Commit cfa9652

Browse files
author
Christian Bender
authored
Merge pull request TheAlgorithms#220 from TheAlgorithms/changed_parenthesis.c
BUG fix data_structures/stack/parenthesis.c
2 parents b5e5bb1 + a80d748 commit cfa9652

File tree

2 files changed

+115
-89
lines changed

2 files changed

+115
-89
lines changed

data_structures/stack/balanced parenthesis using stack in C

Lines changed: 0 additions & 89 deletions
This file was deleted.

data_structures/stack/parenthesis.c

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
#include <assert.h>
5+
6+
#define SIZE 100
7+
8+
struct node
9+
{
10+
char data;
11+
struct node *link;
12+
};
13+
14+
int c = 0; // c used as counter to check if stack is empty or not
15+
struct node *head; //declaring head pointer globally assigned to NULL
16+
17+
void push(char x) //function for pushing
18+
{
19+
struct node *p = head, *temp;
20+
temp = (struct node *)malloc(sizeof(struct node));
21+
temp->data = x;
22+
if (head == NULL) //will be execute only one time i.e, 1st time push is called
23+
{
24+
head = temp;
25+
p = head;
26+
p->link = NULL;
27+
c++;
28+
}
29+
else
30+
{
31+
temp->link = p;
32+
p = temp;
33+
head = p;
34+
c++;
35+
}
36+
}
37+
38+
char pop(void) //function for pop
39+
{
40+
char x;
41+
struct node *p = head;
42+
x = p->data;
43+
head = p->link;
44+
free(p);
45+
c--;
46+
return x;
47+
}
48+
49+
int isBalanced(char *s)
50+
{
51+
int i = 0;
52+
char x;
53+
while (s[i] != '\0') //loop for covering entire string of brackets
54+
{
55+
// printf("\t s[i]=%c\n", s[i]); //DEBUG
56+
if (s[i] == '{' || s[i] == '(' || s[i] == '[') //if opening bracket then push
57+
push(s[i]);
58+
else
59+
{
60+
if (c <= 0) //i.e, stack is empty as only opening brackets are added to stack
61+
return 0;
62+
63+
x = pop();
64+
if (x == '{' && s[i] != '}')
65+
return 0;
66+
if (x == '[' && s[i] != ']')
67+
return 0;
68+
if (x == '(' && s[i] != ')')
69+
return 0;
70+
}
71+
i++;
72+
}
73+
74+
//at end if stack is empy which means whole process has been performed correctly so return 1
75+
return (c == 0) ? 1 : 0;
76+
}
77+
78+
void destroyStack(void)
79+
{
80+
struct node *p = head;
81+
if (c > 0)
82+
{
83+
while (p->link)
84+
{
85+
struct node *tmp = p;
86+
p = p->link;
87+
free(tmp);
88+
}
89+
90+
c = 0;
91+
}
92+
}
93+
94+
int main(void)
95+
{
96+
int t;
97+
printf("\t\tBalanced parenthesis\n\n");
98+
printf("\nPlease enter the number of processing rounds? ");
99+
scanf("%d", &t);
100+
for (int a0 = 0; a0 < t; a0++)
101+
{
102+
char s[SIZE];
103+
printf("\nPlease enter the expression? ");
104+
scanf("%s", s);
105+
106+
if (isBalanced(s))
107+
printf("\nYES\n");
108+
else
109+
printf("\nNO\n");
110+
111+
/* tidy up stack for new round */
112+
destroyStack();
113+
}
114+
return 0;
115+
}

0 commit comments

Comments
 (0)