Skip to Content
Course content

58: Implementing a Stack and Queue

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're working in a busy cafeteria. You've got a stack of clean plates sitting on the counter. When you add a new plate, you put it right on top of the pile. When a customer needs a plate, they take the one from the top. The last plate you put down is the very first one that gets taken. That's a Stack.

Now, imagine you're standing in line at a coffee shop. You're the first person in line, so you're the first person the barista serves. The person who arrives last has to wait until everyone in front of them is gone. That's a Queue.

In PHP, we can implement both of these using arrays, but the magic lies in which array functions we choose. While you could just use raw arrays everywhere, wrapping these in classes makes your code much more predictable and prevents some of the weird bugs that happen when you accidentally treat a queue like a stack.

Building a LIFO Stack for "Undo" Operations

Since a stack is Last-In, First-Out (LIFO), we only care about one end of the array: the end. I like to think of this as the "top" of the stack. In PHP, array_push() and array_pop() are your best friends here. They both operate on the end of the array, which is incredibly efficient.

class UndoStack {
    private array $history = [];

    public function pushAction(string $action): void {
        // We add the action to the top of the stack
        array_push($this->history, $action);
    }

    public function undo(): ?string {
        if ($this->isEmpty()) {
            return null;
        }
        // The last action pushed is the first one popped off
        return array_pop($this->history);
    }

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

// Let's see it in action
$editor = new UndoStack();
$editor->pushAction("Typed 'Hello'");
$editor->pushAction("Typed ' World'");
$editor->pushAction("Changed font to Bold");

echo $editor->undo(); // Outputs: Changed font to Bold
echo $editor->undo(); // Outputs: Typed ' World'

Managing a FIFO Queue for Background Tasks

A queue is First-In, First-Out (FIFO). We still add items to the end, but we take them from the front. To do this in PHP, we use array_push() to enqueue and array_shift() to dequeue. array_shift() is the key here—it pulls the first element off and re-indexes the rest of the array.

One quick heads-up: array_shift() is slower than array_pop() because PHP has to move every other element in the array down one spot. For a few hundred items, you won't notice. For a million? You'll want a different data structure, like SplQueue. But for most day-to-day logic, this array approach is the standard way to go.

class PrintJobQueue {
    private array $jobs = [];

    public function enqueue(string $documentName): void {
        // Add to the end of the line
        array_push($this->jobs, $documentName);
    }

    public function dequeue(): ?string {
        if ($this->isEmpty()) {
            return null;
        }
        // Remove from the front of the line
        return array_shift($this->jobs);
    }

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

$printer = new PrintJobQueue();
$printer->enqueue("Quarterly_Report.pdf");
$printer->enqueue("Vacation_Photo.jpg");
$printer->enqueue("Resume_Final_v2.docx");

echo $printer->dequeue(); // Outputs: Quarterly_Report.pdf
echo $printer->dequeue(); // Outputs: Vacation_Photo.jpg



📋 Practical Task

Build a Browser History Navigator

Your task is to create a system that mimics how a web browser handles the "Back" button. You will need to implement two stacks: a currentHistoryStack and a forwardHistoryStack.

Requirements:

  • Create a class BrowserNavigator.
  • Implement a visit(string $url) method: This should push the new URL onto the currentHistoryStack and clear the forwardHistoryStack (because once you visit a new page, you can't go "forward" anymore).
  • Implement a goBack() method: This should pop the current page from the currentHistoryStack and push it onto the forwardHistoryStack, returning the new top of the current stack.
  • Implement a goForward() method: This should pop from the forwardHistoryStack and push it back onto the currentHistoryStack.

Test your implementation by visiting three different URLs, going back twice, visiting a new URL, and then attempting to go forward (which should now be impossible).

Rating
0 0

There are no comments for now.

to be the first to leave a comment.