|
24 | 24 | * |
25 | 25 | * The singly linked list itself is the logical container for all the |
26 | 26 | * list's elements. The list needs to know which element is the first |
27 | | - * element. It does *not* need to * know the order of the list items |
| 27 | + * element. It does *not* need to know the order of the list items |
28 | 28 | * themselves, because each element is responsible for knowing which |
29 | 29 | * one comes after it. |
30 | 30 | */ |
@@ -52,25 +52,26 @@ class Singly_Linked_List { |
52 | 52 | */ |
53 | 53 | public function appendElement ($value = null) { |
54 | 54 | // Find the last element in the list. |
55 | | - $last_element = $this->end(); |
| 55 | + $last_element = $this->getLastElement(); |
56 | 56 |
|
57 | | - // If there are no elements in the list, the "last element" |
58 | | - // will actually be a `null` value. |
59 | | - if (null === $last_element) { |
60 | | - // In that case, we make a new element, |
61 | | - // and assign that element to the beginning of the list. |
62 | | - $this->first = new Singly_Linked_List_Element($value); |
63 | | - } else { |
64 | | - // If there are already elements in the list, we set the |
65 | | - // new element to its previous element's `$next` member. |
| 57 | + if ($last_element instanceof Singly_Linked_List_Element) { |
| 58 | + // If there are already elements in the list, we add the |
| 59 | + // new element to the end of the list by making the last |
| 60 | + // element's `$next` variable point to the new element. |
66 | 61 | $last_element->next = new Singly_Linked_List_Element($value); |
| 62 | + } else { |
| 63 | + // Otherwise we make a new element to be the beginning of |
| 64 | + // the list. |
| 65 | + $this->first = new Singly_Linked_List_Element($value); |
67 | 66 | } |
68 | 67 | } |
69 | 68 |
|
70 | 69 | /** |
71 | | - * Seek to the end of the list. |
| 70 | + * Find the element at the end of the list. |
| 71 | + * |
| 72 | + * @return null|Singly_Linked_List_Element |
72 | 73 | */ |
73 | | - public function end () { |
| 74 | + public function getLastElement () { |
74 | 75 | // Start at the beginning. |
75 | 76 | $current_element = $this->first; |
76 | 77 |
|
|
0 commit comments