This is my Kotlin implementation of stack data structure
Stack is a generic collection of elements, which is implementing the LIFO (Last-In, First-Out): when you add several items to the stack, the only way to get the first one is to exclude all the following ones. You can:
- add element to the stack,
- exclude and return the last element,
- return it without excluding,
- know if the stack is empty,
- set stack container size
- and create a new stack, containing the elements of the initial stack, on which some operation was done.
Object of class "Stack" can be created using three different constructors:
- With parameter "size": this way you create an instance of Stack of a particular length, which you pass as a parameter.
- With parameter "collection": this way you create an instance of Stack and fill it completely with a Kotlin ArrayList you pass as a conctructor.
- Without parameters: this way you create an instance of an empty Stack.
- elements: ArrayList<T?> - stack itself, realized as an instance of a Kotlin ArrayList.
- length: Int - maximum capasity of this Stack (can be modified externally using "setSize" function).
- upperIndex: Int - index of the topmost element of Stack (if it's equal to the size property it means, that the Stack is full).
- With parameter "size": checks if size is positive integer (throws an exception if otherwise) and initializes properties of the class.
- With parameter "collection": gets a Kotlin ArrayList of data, initializes properties of the class.
- Without parameters: initializes properties of the class (size to 0 and stack to 0 size Kotlin ArrayList). (NOTE: upperIndex property is always set to 0 value when initialized, exept for the case, when a collection of data is passed to the constructor - in this case upperIndex property is set equal to the size property.)
- push(element: T?) - adds an element of type of the Stack to the Stack.
- pop(): T? - removes last added element from the Stack and returns it.
- top(): T? - returns last added element of the Stack without removing it.
- isEmpty(): Boolean - returns true if the upperIndex property is equal to 0, otherwise - returns false.
- setSize(value: Int) - checks if provided parameter's value is less than value of upperIndex property and if so - throws an exception, otherwise sets size property to the parameter value.
- map(mapper: (T?) -> T?) : Stack - applies some function passed as a parameter to every element of a Stack and returns a new Stack of these updated elements.
- isMonotone(collection: ArrayList<T?>): Boolean - checks if the colection passed as a parameter is monotone (if there are any null elements, they aren't surrounded by non-null elements).
- getUpperIndex(collection: ArrayList<T?>): Int - returns the index of the last non-null element in a row.