forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PHP 8 version for a linked-list stack implementation.
- Loading branch information
1 parent
8d94439
commit 7f082b9
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
*/ |