Exercises for Lesson 6
Exercise 1: Implementing a stack using a list
Consider the following interface for the Stack ADT:
interface Stack {
fun push(item: Int)
fun pop(): Int
fun peek(): Int
fun isEmpty(): Boolean
}Write a class ListStack that implements this interface using a MutableList as its underlying data store.
Note that you can also override a function to be able to print your ListStack directly:
/* Return a string representing this ListStack. */
override fun toString(): String {
// TODO
}Here is a main function you could use to test your code:
fun main() {
val s = ListStack()
s.push(2025)
s.push(9)
s.push(26)
println("Elements present in stack: ")
println(s)
println("" + s.pop() + " popped from stack")
println("Top element is: " + s.peek())
println("Elements present in stack: ")
println(s)
}Exercise 2: Validating proper nesting
We can say that a sequence of operations (for example, lock/unlock requests) is “properly nested” we complete requests in the reverse order that we start them. For example, the following are properly nested sequences (assuming the first occurrence of a letter marks the start and the second marks the end for that pair):
- AA
- ABBA
- ABCCBA
- ABBCCA
However, the following are not properly nested sequences:
- ABAB
- ABCACB
How could you use a stack to determine whether a given input string is properly nested? Try to write some code to solve this!