How to resolve the algorithm Queue/Definition step by step in the Groovy programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Queue/Definition step by step in the Groovy programming language

Table of Contents

Problem Statement

Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.

Operations:

Errors:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Queue/Definition step by step in the Groovy programming language

Source code in the groovy programming language

class Queue {
    private List buffer

    public Queue(List buffer =  new LinkedList()) {
        assert buffer != null
        assert buffer.empty
        this.buffer = buffer
    }

    def push (def item) { buffer << item }
    final enqueue = this.&push
    
    def pop() {
        if (this.empty) throw new NoSuchElementException('Empty Queue')
        buffer.remove(0)
    }
    final dequeue = this.&pop
    
    def getEmpty() { buffer.empty }
    
    String toString() { "Queue:${buffer}" }
}


def q = new Queue()
assert q.empty

['Crosby', 'Stills'].each { q.push(it) }
assert !q.empty
['Nash', 'Young'].each { q.enqueue(it) }
println q
assert !q.empty
assert q.pop() == 'Crosby'
println q
assert !q.empty
assert q.dequeue() == 'Stills'
println q
assert !q.empty
assert q.pop() == 'Nash'
println q
assert !q.empty
q.push('Crazy Horse')
println q
assert q.dequeue() == 'Young'
println q
assert !q.empty
assert q.pop() == 'Crazy Horse'
println q
assert q.empty
try { q.pop() } catch (NoSuchElementException e) { println e }
try { q.dequeue() } catch (NoSuchElementException e) { println e }


  

You may also check:How to resolve the algorithm Zero to the zero power step by step in the Crystal programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Weird numbers step by step in the Sidef programming language
You may also check:How to resolve the algorithm Delete a file step by step in the Lang programming language