Which data structure is most suitable for checking whether the brackets in an expression such as {} are balanced?
Correct answer A. Stack
Push each opening bracket onto a stack; on a closing bracket, pop and check that it matches the same type. The most recently opened bracket must close first, which is exactly LIFO order. The expression is balanced if every closing bracket matches and the stack is empty at the end. A queue would compare the wrong brackets because it returns the oldest one.
Answer checked How we write and check questions
Discussion