Hejsa!
Thought I had my problems solved - but then apparently not...
I expect my new code to produce:
It is empty
5 and tail is: 5
4 5 and tail is: 5
4 5 6 and tail is: 6
4 5 6 7 and tail is: 7
6 and tail is: 6
6 7 and tail is: 7
5 6 7 and tail is: 7
4 5 6 7 and tail is: 7
Hello world
But it actually produces:
It is empty
5 and tail is: 5
4 5 and tail is: 4
4 6 and tail is: 6
4 6 7 and tail is: 7
6 and tail is: 6
6 7 and tail is: 7
5 6 7 and tail is: 7
4 5 6 7 and tail is: 7
Hello world
I suspect either addToHead or IntNode() is wrong.
This is my new code:
<?php
// a node in an integer singly linked list class
class IntNode {
var $info; // integer
var $next; // IntNode
function IntNode($i,$n) {
$this->info = $i;
$this->next = $n;
}
}
?>
<?php
// singly linked list class to store integers
class IntSLList {
var $head; // IntNode
var $tail; // IntNode
function IntSLList() {
$this->head = null;
$this->tail = null;
}
function isEmpty() {
return ($this->head == null);
}
function addToHead($el) {
$this->head = new IntNode($el,$this->head);
if ($this->tail == null) {
$this->tail = &$this->head;
}
}
function addToTail($el) {
if (!$this->isEmpty()) {
$this->tail->next = new IntNode($el,null);
$this->tail = &$this->tail->next;
} else {
$this->tail = new IntNode($el,null);
$this->head = &$this->tail;
}
}
function printAll() {
$tmp = $this->head;
while ($tmp != null) {
print "$tmp->info ";
$tmp = $tmp->next;
}
print "and tail is: " . $this->tail->info;
print "<br>\n";
}
}
?>
<?php
include "IntNode.obj";
include "IntSLList.obj";
$test1 = new IntNode(2,null);
$test2 = new IntNode(3,$test1);
$test3 = new IntSLList();
if ($test3->isEmpty()) {
print "It is empty<br />";
} else {
print "There's something here<br />";
}
$test3->addToHead(5);
$test3->printAll();
$test3->addToHead(4);
$test3->printAll();
$test3->addToTail(6);
$test3->printAll();
$test3->addToTail(7);
$test3->printAll();
$test3 = new IntSLList();
$test3->addToTail(6);
$test3->printAll();
$test3->addToTail(7);
$test3->printAll();
$test3->addToHead(5);
$test3->printAll();
$test3->addToHead(4);
$test3->printAll();
?>
<html><head><title>Hello world</title></head>
<body>
Hello world
</body>
</html>