stack struct function

ello

I am writing the balance function that should figure out whether the left and right parens ( ) , the left and right brackets [ ] , and the left and right curly brackets { } are properly matched and nested in the string arg. For instance,

examples "(sldkj[slkdfjk{slkdfjsl(sldkjf(lkjsd)slkdfj)sldkfj}slkdjf]sldkfj)": balanced,
"(((( [[[[ ]]]]{{{{ }}}} ))))": balanced
"([)]": not balanced (even though we have left & right paren and a left & right bracket)
"": balanced, no parens means no mismatch

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
  bool balanced(const string & line)
{
	Stack sk;
	initialize(sk);
	if (line.size() > STACK_SIZE) die("stack overflow");
	for (unsigned i = 0; i < line.size(); i++)
	{
		switch (line[i])
		{
		case '(':
			push(sk, line);
			if (line[i] == ')')
			{
				if (top(sk)== "(") return 0;
				else  pop(sk); 
			} 
		case '[':
			push(sk, line);
			if (line[i] == ']')
			{
				if (top(sk) == "[") return 0;
				else  pop(sk);
			}		
		case'{':
			push(sk, line);
			if (line[i] == '}')
			{
				if (top(sk) == "{") return 0;
				else  pop(sk); 
			}	
		default:
			;
		}//switch
	}//for
	
	if (elements(sk) == 0) return 1;
	else return 0;
}//balanced 
Topic archived. No new replies allowed.