Exercise: Generic Stack Implementation
Enhance your Kotlin skills by creating a generic stack class that can store elements of any data type.
We'll cover the following
Problem statement
Implement a generic stack class named Stack<T>
that can store elements of any data type.
Instructions
In the given main
code, you are provided with the usage of a generic Stack
class designed to accommodate elements of any data type. Your task is to complete the implementation of generic stack operations. The class should support the following standard stack operations:
push(item: T)
: It adds an item of typeT
to the top of the stack.pop(): T?
: It removes and returns the item from the top of the stack. It returns an item of typeT
, ornull
if the stack is empty.peek(): T?
: It returns the item from the top of the stack without removing it. It returns an item of typeT
, ornull
if the stack is empty.isEmpty(): Boolean
: It checks if the stack is empty and returnstrue
if it is, orfalse
if it contains elements.size(): Int
: It returns the number of elements currently in the stack as an integer value.
Tip: You can utilize a mutable list as a property of the class to store the elements. To pop an element, use the
removeAt
method.
The actual output when running the provided code should be as follows:
Get hands-on with 1400+ tech skills courses.