Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Last active August 23, 2016 10:20
Show Gist options
  • Save antoniopicone/17e39696fa666cc59d1867440bda6662 to your computer and use it in GitHub Desktop.
Save antoniopicone/17e39696fa666cc59d1867440bda6662 to your computer and use it in GitHub Desktop.
A simple PHP implementation of a Stack
<?php
// I could use array_push and array_pop with an array, as PHP already implements internally a stack with a doubly linked list
class Node {
public $data;
public $next;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
public function getData()
{
return $this->data;
}
}
class Stack {
private $top;
public function __construct()
{
$this->top = NULL;
}
public function peek()
{
if($this->isEmpty()) throw new Exception("The stack is empty");
return $this->top->getData();
}
public function isEmpty() {
return $this->top == NULL;
}
public function push($data) {
$new_node = new Node($data);
$new_node->next = $this->top;
$this->top = &$new_node;
}
public function pop() {
if($this->isEmpty()) throw new Exception("The stack is empty");
$top = $this->top;
$this->top = $top->next;
return $top->getData();
}
}
$s = new Stack();
$s->push(3);
$s->push(4);
echo $s->peek()."\n";
$s->pop();
echo $s->peek()."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment