Introduction: Stacks and Queues

Welcome to an exciting exploration of two fundamental data structures: Stacks and Queues in PHP! In computing, these structures help organize data efficiently. Stacks and Queues are akin to stacking plates and standing in a line, respectively. For queues, we will use PHP's SplQueue, and for stacks, we will utilize a simple array, though SplStack is also an option, as we'll mention later.

Stacks: Last In, First Out (LIFO)

A Stack adheres to the "Last In, First Out" or LIFO principle. It's similar to a pile of plates where the last plate added is the first one to be removed. In this section, we will use a simple array to implement a stack. The primary operations for stacks involve adding and removing elements:

  • push: Adds an element to the top of the stack.
  • pop: Removes the top element from the stack.
  • isEmpty: Checks whether the stack is empty.
  • top: Returns the top element of the stack without removing it.

Let's explore this concept using a pile of plates as an analogy.

PHP
<?php

class StackOfPlates {
    private array $stack;

    public function __construct() {
        $this->stack = array();
    }

    // Inserts a plate at the top of the stack
    public function addPlate(mixed $plate): void {
        array_push($this->stack, $plate); // Using array_push to add a plate
    }

    // Removes the top plate from the stack
    public function removePlate(): mixed {
        if (empty($this->stack)) { // Using isEmpty to check if stack is empty
            return "No plates left to remove!";
        }
        return array_pop($this->stack); // Using array_pop to remove and return the top plate
    }

    public function isEmpty(): bool {
        return empty($this->stack);
    }

    public function top(): mixed {
        if (empty($this->stack)) {
            return "No plates in the stack!";
        }
        return end($this->stack); // Using end to get the top element
    }    
}

// Example usage:
$plates = new StackOfPlates();
$plates->addPlate("Plate");
$plates->addPlate("Another Plate");

echo "Removed: " . $plates->removePlate() . "\n"; // Outputs: Removed: Another Plate

?>

The last plate added was removed first, demonstrating the LIFO property of a stack. While we used an array here for illustration, PHP's Standard PHP Library contains the SplStack class that can also be used for stack operations, providing more functionality and consistency.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal