Advertisement
markruff

kotlin - queue

Jul 24th, 2023 (edited)
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.14 KB | None | 0 0
  1. class Queue<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 enqueue(v: T) {
  14.         var newNode = Node<T>(v)
  15.         if (head == null) {
  16.             head = newNode
  17.         } else {
  18.             var current: Node<T> = head ?: return // can't be null
  19.             while (current.next != null) {
  20.                 current = current.next ?: return // can't be null
  21.             }
  22.             current.next = newNode
  23.         }
  24.         length++
  25.     }
  26.    
  27.     fun dequeue(): T? {
  28.         val dequeuer = head ?: return null
  29.         // immutable shadow
  30.         val retval: T = dequeuer.value
  31.         head = dequeuer.next
  32.         length--
  33.         return retval
  34.     }
  35.  
  36.     fun isEmpty(): Boolean = length == 0
  37.    
  38.     fun print() {
  39.         var current: Node<T>? = head
  40.         print ("[")
  41.         while (current != null) {
  42.             print(current.value)
  43.             current = current.next
  44.             if (current != null) print(", ")
  45.         }
  46.         println("]")
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement