Skip to content

Commit be27a46

Browse files
committed
Add C Solution for 20-Valid-Parenthesis
1 parent 0b6e3c5 commit be27a46

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

c/20-Valid-Parenthesis.c

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
2+
struct Node {
3+
char val;
4+
struct Node* next;
5+
};
6+
7+
struct Stack {
8+
struct Node* head;
9+
size_t len;
10+
};
11+
12+
struct Node* Node(char val, struct Node* next) {
13+
struct Node* root = (struct Node*)malloc(sizeof(struct Node));
14+
root -> next = next;
15+
root -> val = val;
16+
return root;
17+
}
18+
19+
struct Stack* Stack() {
20+
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
21+
stack -> len = 0;
22+
stack -> head = NULL;
23+
return stack;
24+
}
25+
26+
void append(struct Stack* stack, char val) {
27+
struct Node* node = Node(val, stack -> head);
28+
stack -> head = node;
29+
stack -> len += 1;
30+
}
31+
32+
char pop(struct Stack* stack) {
33+
if (stack -> head == NULL) {
34+
return NULL;
35+
}
36+
char val = stack -> head -> val;
37+
struct Node* deleteNode = stack -> head;
38+
stack -> head = stack -> head -> next;
39+
stack -> len -= 1;
40+
free(deleteNode);
41+
return val;
42+
}
43+
44+
void freeStack(struct Stack* stack) {
45+
while (pop(stack) != NULL) {
46+
pop(stack);
47+
}
48+
free(stack);
49+
}
50+
51+
char opposite_parenthesis(char closing) {
52+
char opening = NULL;
53+
if (closing == ')') {
54+
opening = '(';
55+
} else if (closing == '}') {
56+
opening = '{';
57+
} else if (closing == ']') {
58+
opening = '[';
59+
}
60+
return opening;
61+
}
62+
63+
bool isValid(char * s){
64+
65+
struct Stack* stack = Stack();
66+
char* chr;
67+
68+
for (chr = s; *chr != '\0'; chr++) {
69+
if (opposite_parenthesis(*chr) == NULL) {
70+
append(stack, *chr);
71+
} else if (stack -> len != 0 && opposite_parenthesis(*chr) == pop(stack)) {
72+
continue;
73+
} else {
74+
return false;
75+
}
76+
}
77+
return stack -> len == 0;
78+
}

0 commit comments

Comments
 (0)