1<?php
2
3require 'Structures/LinkedList/Single.php';
4
5/* To do anything useful with a linked list, you need to
6 * extend the Node class to hold data associated with the
7 * node. In this case, we're just going to hold a single
8 * integer in the $_my_number property.
9 */
10class LinkNodeTester extends Structures_LinkedList_SingleNode {
11    protected $_my_number;
12    protected $_my_letter;
13
14    function __construct($num, $letter) {
15        $this->_my_number = $num;
16        $this->_my_letter = $letter;
17    }
18
19    function getNumber() {
20        return $this->_my_number;
21    }
22
23    function getLetter() {
24        return $this->_my_letter;
25    }
26
27    function setNumb($numb) {
28        $this->_my_number = $numb;
29    }
30
31    function __toString() {
32        return "{$this->getNumber()}";
33    }
34}
35
36/* To enable key=>value iteration, we must override the default key()
37 * method in Structures_LinkedList_Single to return a meaningful value */
38class LinkListTester extends Structures_LinkedList_Single {
39    function key() {
40        return $this->current()->getLetter();
41    }
42}
43
44/* Now we'll create some instances of the new class */
45$node1 = new LinkNodeTester(1, 'a');
46$node2 = new LinkNodeTester(2, 'b');
47$node3 = new LinkNodeTester(3, 'c');
48$node4 = new LinkNodeTester(4, 'd');
49$node5 = new LinkNodeTester(5, 'e');
50
51/* Start by instantiating a list object.
52 * You can either pass the first node to the constructor,
53 * or leave it null and add nodes later.
54 */
55$list = new LinkListTester($node1); // 1
56
57/* appendNode() adds a node to the end of the list */
58$list->appendNode($node2); // 1-2
59
60/* prependNode() adds a node to the start of the list */
61$list->prependNode($node3); // 3-1-2
62
63/* insertNode($new_node, $reference_node, $before) adds a node
64 * before the reference node if the third parameter is true,
65 * or after the reference node if the third parameter is false
66 */
67$list->insertNode($node4, $node2, true); // 3-1-4-2
68
69/* current() returns the current pointer node in the list */
70$link = $list->current(); // 1
71
72/* You can iterate through a list with the next() method */
73do {
74    print $link->getNumber();
75} while ($link = $list->next()); // 1-4-2
76
77/* rewind() resets the pointer to the root node of the list */
78$link = $list->rewind(); // 3
79
80/* You can also iterate through a list with foreach() */
81foreach ($list as $bull) {
82  print $bull->getNumber();
83} // 3-1-4-2
84
85/* Override the key() method to enable $key=>$value iteration */
86foreach ($list as $key=>$value) {
87  print "$key => $value\n";
88}
89
90/* end() resets the pointer to the last node of the list */
91$link = $list->end(); // 2
92
93/* You can iterate backwards through a list with previous() */
94do {
95    print $link->getNumber();
96} while ($link = $list->previous()); // 2-4-1-3
97?>
98