Skip to content

Commit

Permalink
PHP 8 version for a linked-list stack implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
paulovitorbal committed Oct 26, 2021
1 parent 8d94439 commit 7f082b9
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions stack/php/linked_stack.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

class Node {
public function __construct(private int $value, private ?Node $next = null){

}
public function push(int $value): Node {
return new Node($value, $this);
}

public function print():void{
echo $this->value . ' ';
$this->next?->print();
}

public function pop():array{
return [
$this->value,
$this->next
];
}
}

$root = new Node(0);
$root->print();
echo PHP_EOL;
$root = $root->push(1);
$root->print();
echo PHP_EOL;
$root = $root->push(2);
$root->print();
echo PHP_EOL;
[$value, $root] = $root->pop();
echo 'popped value: ' . $value . ' ' . PHP_EOL;
$root->print();
echo PHP_EOL;
[$value, $root] = $root->pop();
echo 'popped value: ' . $value . ' ' . PHP_EOL;
$root->print();
echo PHP_EOL;
[$value, $root] = $root->pop();
echo 'popped value: ' . $value . ' ' . PHP_EOL;
$root?->print();

/**
Produced output:
0
1 0
2 1 0
popped value: 2
1 0
popped value: 1
0
popped value: 0
*/

0 comments on commit 7f082b9

Please sign in to comment.