Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Stack<T> {
- class Node<T>(v: T) {
- val value: T = v
- var next: Node<T>? = null
- }
- var head: Node<T>? = null
- var length: Int = 0
- private set
- fun push(v: T) {
- var newNode = Node<T>(v)
- newNode.next = head
- head = newNode
- length++
- }
- fun pop(): T? {
- val popper = head ?: return null
- // immutable shadow
- val retval: T = popper.value
- head = popper.next
- length--
- return retval
- }
- fun isEmpty(): Boolean = length == 0
- fun print() {
- var current: Node<T>? = head
- print ("[")
- while (current != null) {
- print(current.value)
- current = current.next
- if (current != null) print(", ")
- }
- println("]")
- }
- }
- fun main() {
- val s: Stack<Int> = Stack<Int>()
- s.push(1)
- s.push(2)
- s.push(3)
- s.print()
- while(s.length > 0)
- println(s.pop())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement