-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackapp.c
executable file
·98 lines (85 loc) · 1.95 KB
/
stackapp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* stack.c: Stack application. */
/*********************************************************************
** Program Filename: stackapp.c
** Author: Nhu Duong
** Date: July 16, 2018
** Description: Using functions and stack to check the string balance
*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "dynArray.h"
/* ***************************************************************
Using stack to check for unbalanced parentheses.
***************************************************************** */
/* Returns the next character of the string, once reaches end return '0' (zero)
param: s pointer to a string
pre: s is not null
*/
char nextChar(char* s)
{
static int i = -1;
char c;
++i;
c = *(s+i);
if ( c == '\0' )
return '\0';
else
return c;
}
/* Checks whether the (), {}, and [] are balanced or not
param: s pointer to a string
pre: s is not null
post:
*/
int isBalanced(char* s)
{
DynArr *stack;
stack = newDynArr(2);
char cur_char;
char top_stack;
cur_char = nextChar(s);
while (cur_char!= '\0'){
if (cur_char == '(' || cur_char == '[' || cur_char=='{'){
pushDynArr(stack, cur_char);
}
if (cur_char == ')' || cur_char == ']'|| cur_char =='}' ){
// popDynArr(stack);
int sj;
sj= sizeDynArr(stack);
if (sj ==0){
return 0;
}
top_stack = topDynArr(stack);
popDynArr(stack);
}
//
if (cur_char == ')' && top_stack != '('){
return 0;
}
else if (cur_char == ']' && top_stack != '['){
return 0;
}
else if (cur_char == '}' && top_stack != '{'){
return 0;
}
cur_char = nextChar(s);
}
return 1;
//
// if (isEmptyDynArr(stack)== 1){
// return 1;
// }
// return 0;
}
int main(int argc, char* argv[]){
char* s=argv[1];
int res;
printf("Assignment 2\n");
res = isBalanced(s);
if (res)
printf("The string %s is balanced\n",s);
else
printf("The string %s is not balanced\n",s);
return 0;
}