Created
January 12, 2023 07:54
-
-
Save matusstafura/4bd1beeba61f1995b3fcd18a77bf87c6 to your computer and use it in GitHub Desktop.
Basic operations in stacks in PHP
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
<?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