Skip to content

Instantly share code, notes, and snippets.

@matusstafura
Created January 12, 2023 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matusstafura/4bd1beeba61f1995b3fcd18a77bf87c6 to your computer and use it in GitHub Desktop.
Save matusstafura/4bd1beeba61f1995b3fcd18a77bf87c6 to your computer and use it in GitHub Desktop.
Basic operations in stacks in PHP
<?php
class Node
{
public $value;
public $next;
public function __construct($value)
{
$this->value = $value;
$this->next = null;
}
}
class Stack
{
public $top;
public $height;
public function __construct(public $value)
{
$newNode = new Node($value);
$this->top = $newNode;
$this->height = 1;
}
public function printStack()
{
$temp = $this->top;
while ($temp != null) {
echo $temp->value."\n";
$temp = $temp->next;
}
}
public function push($value)
{
$newNode = new Node($value);
if ($this->height == 0) {
$this->top = $newNode;
} else {
$newNode->next = $this->top;
$this->top = $newNode;
}
$this->height++;
}
public function pop()
{
if ($this->height == 0) {
return null;
}
$temp = $this->top;
$this->top = $this->top->next;
$temp->next = null;
$this->height--;
return $temp;
}
}
$s = new Stack('youtube.com');
$s->push('google.com');
$s->push('gmail.com');
$s->pop();
$s->printStack();
// ARRAYS
// $stack = [];
// array_push($stack, 'youtube.com');
// array_push($stack, 'google.com');
// array_push($stack, 'gmail.com');
// array_pop($stack);
// $stack;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment