Skip to content

Instantly share code, notes, and snippets.

@Vishal1297
Last active January 26, 2021 05:11
Show Gist options
  • Save Vishal1297/d9a330552bf816665eb64e3ee78823a4 to your computer and use it in GitHub Desktop.
Save Vishal1297/d9a330552bf816665eb64e3ee78823a4 to your computer and use it in GitHub Desktop.
Stack Implementaion Using Kotlin Array Class
class Main {
public static void main(String[] args) {
Stack stack = new Stack();
System.out.println(stack.isEmpty() ? "Empty" : "Not Empty");
stack.push(12);
stack.push(13);
System.out.println("Find 14 : Found At Index " + stack.search(14));
stack.push(14);
stack.push(15);
System.out.println("Elements : ");
stack.printStack();
System.out.println(stack.isFull() ? "Full" : "Not Full");
System.out.println(stack.isEmpty() ? "Empty" : "Not Empty");
stack.pop();
stack.pop();
stack.pop();
System.out.println("Elements : ");
stack.printStack();
System.out.println("Peek " + stack.peek());
stack.pop();
stack.pop();
System.out.println(stack.isEmpty() ? "Empty" : "Not Empty");
System.out.println("Find 14 : Found At Index " + stack.search(14));
System.out.println("Elements : ");
stack.printStack();
}
}
// Stack Implementaion Using Kotlin
class Stack {
private var size = 5
private var stack = Array<Any>(size) {}
private var stackSize = 0
fun setSize(size: Int) {
this.size = size
}
fun push(element: Any) {
if (isFull()) println("Stack Overflow while adding $element")
else stack[stackSize++] = element
}
fun pop(): Any {
if (isEmpty()) {
println("Stack Underflow")
return 0
}
val lastIndex = stack.size - 1
val lastElement = stack[lastIndex]
stack[lastIndex] = 0
stackSize--
return lastElement
}
fun peek(): Any {
return if (isEmpty())
"Stack is Empty"
else
stack[stackSize - 1]
}
fun search(element: Any): Int {
for (index in 0 until stackSize) {
if (stack[index] === element) return index
}
return -1
}
fun isFull(): Boolean = stackSize >= stack.size
fun isEmpty(): Boolean = stackSize <= 0
fun printStack() {
for (index in 0 until stackSize) print("${stack[index]} ")
println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment