Exercises
Stacks #1

What is a stack (at the logical level)?

Give an example of a stack in everyday life.

1. In problems 1 and 2, find the output of each program fragment. Show your work.

```apstack S; int x = 2, y = 3; S.push(x); S.push(2*y); S.push(4); S.pop(y); S.push(7); S.pop( ); x = S.top( ); int n = S.length( ); for(int i=0; i<n;i++)    S.push(n); while( ! S.isEmpty( ) ) {    S.pop(y);    System.out.println(y); } System.out.println("x is " +  x); ```

2. ``` apstack R, S, T; for(int i=10; i<50; i+=10)    S.push( i ); T = S; int a, b; while ( ! S.isEmpty( ) ) {    S.pop(a);    R.push(a); } int n = T.length( ); for(int i=0; i<n; i++) {    R.pop(a);    T.pop(b);    System.out.println(a + " " + b); } System.out.println(" R T"); ```

3. Write each of the following functions that print the contents of a stack across a page leaving the stack unchanged.

``` void displayTopFirst(apstack S) //pre- the stack has been initialized //post- stack's elements are displayed across the page // without spaces, top first, followed by an end-of- // line, the stack is unchanged {    ... } ```

4. ```void displayTopLast(apstack S) //pre- the stack has been initialized //post- stack's elements are displayed across the page // without spaces, top last, followed by an end-of-line; // the stack is unchanged {    ... } ```

5. Write a Boolean function which returns `true` if an `String` parameter contains matching and non-overlapping brackets -` ( ) [ ] { }`; otherwise, the function returns `false`. For example,
• `"[N(ov)(emb)er]1st"` returns true
• `"{Oc[t}ober2]3rd"` returns false

Hint: Push opening symbols onto a stack of characters. When a closing symbol is found, pop the stack to see if the brackets match.

```Boolean bracketsMatch(String str) {    ... } ```

Continue to:  Unit 5 / Prev / Next