NUIMCrest CS210 - Algorithms and Data Structures I
Department of Computer Science
National University of Ireland, Maynooth

T Naughton, NUIM
Back to CS210 home


Laboratory Sheet 4

The stack This lab exam will allow you to increase your understanding of an elementary data structure: the (pushdown) stack. Answer both problems, 4.1 (a straightforward iteration problem) and 4.2 (a stack problem).

Reminder...


Problem 4.1 Write a function that takes an array of characters as a parameter. This array will consist of a sequence of bracket characters, `(' and `)'. Your program must check if the sequence contains the same number of open `(' brackets as close `)' brackets. So, just use a while loop to count the occurances of brackets of each type and print "valid" if they are the same, and "invalid" otherwise. For example, the sequences ")()(" and "(())" are valid, the sequence "(()" is invalid. Your pseudocode should have the following format.

void EqualBrackets(char a[]) {
  /* This function checks if the numbers of occurances of
  ** each bracket type are equal.
  */

  // Your code here
}


  • Next, imagine we make the problem more difficult. Now all brackets must match. This means that all closing brackets must correspond to a previously opened bracket. Now, ")()(" is invalid, while "(())()" remains valid. Furthermore, imagine that there are more than one type of bracket, and each must match.

  • In lectures, you have been given pseudocode algorithms for the basic functionality of the stack. Use this to solve the next problem.


    Problem 4.2 Continuation of problem 4.1. This time, brackets must match. In addition, the set of possible pairs of brackets is increased to `(' `)', `[' `]', `{' `}', and `<' `>'. For example, "([{}]{}<>" is invalid and "[{}({}){<>}]" is valid. Find a solution to this problem using a stack. Your solution should consist of diagrams/pseudocode. There is no need to code a solution in Java. Rewrite your pseudocode if necessary to ensure that it is clear and neat. If I can't understand it, you'll reveive a poor mark.


    End of sheet