<?php
class Node
{
// always initialize properties
public mixed $data = null;
public ?Node $next = null;
public function __construct(mixed $data)
{
$this->data = $data;
}
}
class Stack
{
// always initialize properties
public ?Node $head = null;
public function push(mixed $data) : void
{
$node = new Node($data);
$node->next = $this->head;
$this->head = $node;
}
public function pop() : mixed
{
if (!$this->head)
{
return 'Stack empty';
}
$data = $this->head->data;
$this->head = $this->head->next;
return $data;
}
}
$ll = new Stack();
echo 'pop(): ' . $ll->pop() . PHP_EOL;
for ($i = 1; $i < 4; $i++) { $ll->push($i); }
var_dump($ll);
echo 'pop(): ' . $ll->pop() . PHP_EOL;
echo 'pop(): ' . $ll->pop() . PHP_EOL;
echo 'pop(): ' . $ll->pop() . PHP_EOL;
echo 'pop(): ' . $ll->pop() . PHP_EOL;
var_dump($ll);
To embed this project on your website, copy the following code and paste it into your website's HTML: