Back to home

Test FileLinked ListRunning Tests
PHP Linked List main image

PHP Linked List

This expects an installation on the system of phpunit.

Test File

Create linked_list_test.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?php require "linked-list.php"; class LinkedListTest extends PHPUnit\Framework\TestCase { public function testInsertFirst() { $n1 = new Node(1); $n2 = new Node(2); $ll = new LinkedList($n1); $ll->insertFirst($n2); $this->assertEquals($ll->size, 2); } public function testGetFirst() { $n1 = new Node(1); $n2 = new Node(2); $ll = new LinkedList($n1); $ll->insertFirst($n2); $this->assertEquals($ll->size, 2); $this->assertEquals($ll->getFirst(), $n2); } }

Linked List

Create linked_list.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <?php class LinkedList { public $size = 0; public $head; function __construct($head = null) { $this->head = $head; if ($head != null) { $this->size = 1; } else { $this->size = 0; } } public function insertFirst($n) { if ($this->head != null) { $tmp = $this->head; $this->head = $n; $n->setNext($tmp); } else { $this->head = $n; } $this->size++; } public function getFirst() { return $this->head; } } class Node { private $data; private $next; function __construct($data = null) { $this->data = $data; } public function getData() { return $this->data; } public function setData($data) { $this->data = $data; } public function getNext() { return $this->next; } public function setNext($next) { $this->next = $next; } }

Running Tests

Change into directory and run phpunit.phar linked_list_test.php.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.