Skip to content

Instantly share code, notes, and snippets.

@meetrajesh
Created October 5, 2012 03:06
Show Gist options
  • Save meetrajesh/3837828 to your computer and use it in GitHub Desktop.
Save meetrajesh/3837828 to your computer and use it in GitHub Desktop.
PHP Linked List Implementation
<?php
class Node {
private $_data;
public $next;
public function __construct($data) {
$this->_data = $data;
}
public function get_data() {
return $this->_data;
}
}
class LinkedList {
private $_head;
private $_tail;
public function __construct($head=null) {
$this->_head = $head;
}
public function add(Node $item) {
if (!$this->_head) {
$this->_head = $item;
$this->_tail = $item;
} else {
$this->_tail->next = $item;
$this->_tail = $item;
}
}
public function print_all() {
$node = $this->_head;
while ($node != null) {
echo $node->get_data() . "\n";
$node = $node->next;
}
}
}
$list = new LinkedList;
$list->add(new Node(3));
$list->add(new Node(4));
$list->add(new Node(5));
$list->add(new Node(6));
$list->add(new Node(7));
$list->print_all();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment