markruff icon

kotlin - queue

markruff | PRO | 07/24/23 09:45:30 AM UTC (Edited) | 0 ⭐ | 11877 👁️ | Never ⏰ | []
Kotlin |

1.14 KB

|

None

|

0 👍

/

0 👎

class Queue<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 enqueue(v: T) {
        var newNode = Node<T>(v)
        if (head == null) {
            head = newNode
        } else {
            var current: Node<T> = head ?: return // can't be null
            while (current.next != null) {
                current = current.next ?: return // can't be null
            }
            current.next = newNode
        }
        length++
    }
    
    fun dequeue(): T? {
        val dequeuer = head ?: return null
        // immutable shadow
        val retval: T = dequeuer.value
        head = dequeuer.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("]")
    }
    
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎