class Node(val data: Int, var next: Node? = null) {
override fun toString(): String {
// displays stack in reverse order
// where top of stack is the right-most element
var output = if (next != null) "$next, " else ""
output += "$data"
return output
}
}
class Stack {
private var top: Node? = null
fun push(data: Int) {
val node = Node(data)
node.next = top
top = node
}
fun pop(): Int? {
val data = top?.data
top = top?.next
return data
}
override fun toString(): String {
var output = "Stack: "
output += if (top != null) "[$top]" else "[]"
return output + " <-top"
}
}
fun main() {
val stack = Stack()
println(stack)
println("${stack.pop()} popped")
stack.push(3)
stack.push(2)
stack.push(1)
println(stack)
println("${stack.pop()} popped")
println(stack)
println("${stack.pop()} popped")
println(stack)
println("${stack.pop()} popped")
println(stack)
println("${stack.pop()} popped")
println(stack)
}
To embed this project on your website, copy the following code and paste it into your website's HTML: