Queues

About

Imagine a line of people waiting to buy tickets at a movie theater or a concert venue. The first person who gets in line is the very first person served, and any newcomer must join at the absolute back of the line.

Because of this, a Queue is known as a FIFO (First In, First Out) data structure. The element that has been waiting the longest is always processed first.

444333111222push()pop()

Complexities

Code Implementations

Python

if __name__ == "__main__":
    q = Queue()
    q.enqueue("Alice")
    q.enqueue("Bob")
    print("Front element (Peek):", q.peek())    # Expected: Alice
    print("Served (Dequeued):", q.dequeue())     # Expected: Alice
    print("Next in line:", q.peek())             # Expected: Bob

C++

int main() {
    Queue q;
    q.enqueue("Alice");
    q.enqueue("Bob");
    
    std::cout << "Front element (Peek): " << q.peek() << std::endl; // Expected: Alice
    q.dequeue();
    std::cout << "Front element after dequeue: " << q.peek() << std::endl; // Expected: Bob
    std::cout << "Queue size: " << q.size() << std::endl; // Expected: 1
    
    return 0;
}

Key Takeaways

Powered by Forestry.md