Advertisement
markruff

kotlin - stack

Jul 23rd, 2023
1,614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.03 KB | None | 0 0
  1. class Stack<T> {
  2.    
  3.     class Node<T>(v: T) {
  4.         val value: T = v
  5.         var next: Node<T>? = null    
  6.     }
  7.    
  8.     var head: Node<T>? = null
  9.    
  10.     var length: Int = 0
  11.         private set
  12.    
  13.     fun push(v: T) {
  14.         var newNode = Node<T>(v)
  15.         newNode.next = head
  16.         head = newNode
  17.         length++
  18.     }
  19.    
  20.     fun pop(): T? {
  21.         val popper = head ?: return null
  22.         // immutable shadow
  23.         val retval: T = popper.value
  24.         head = popper.next
  25.         length--
  26.         return retval
  27.     }
  28.    
  29.     fun isEmpty(): Boolean = length == 0
  30.    
  31.     fun print() {
  32.         var current: Node<T>? = head
  33.         print ("[")
  34.         while (current != null) {
  35.             print(current.value)
  36.             current = current.next
  37.             if (current != null) print(", ")
  38.         }
  39.         println("]")
  40.     }
  41.    
  42. }
  43.  
  44. fun main() {
  45.     val s: Stack<Int> = Stack<Int>()
  46.     s.push(1)
  47.     s.push(2)
  48.     s.push(3)
  49.     s.print()
  50.     while(s.length > 0)
  51.         println(s.pop())
  52. }
Tags: Stack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement