Code: Select all
andCode: Select all
tags where appropriate when posting code. Read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
I am trying to implement a linked list, but havea problem iterating through it when I want to add a node. In order to do this, I need a reference variable (currentNode) to walk through the list, this needs to be a reference because when I use the iteration node to update the list, the original list must show the changes. The only problem is that when I define a reference variable pointing to the head node of my list, and I change it for iteration, the original reference changes with it. With other words, when I make the new reference point to another variable, the original constant ($this) changes with it anybody has a clue on how to solve this?Code: Select all
<?php
class Node{
var $value;
var $next;
function add($number){
$newNode = new Node;
$newNode->value = $number;
//insert at head of the list
if($this->value<$number){
$newNode->next = $this;
return $newNode;
}
$currentNode = & $this;
while($currentNode->next->value>$number and $currentNode->next != NULL){
$currentNode = $currentNode->next;
}
$newNode->next = $currentNode->next;
$currentNode->next = $newNode;
return $this;
}
function printList(){
$currentNode = $this;
while($currentNode != NULL){
echo $currentNode->value."<BR>";
$currentNode = $currentNode->next;
}
}
}
$head = new Node;
$head->value = 4;
$head = $head->add(10);
$head = $head->add(2);
$head->printList();
?>Code: Select all
andCode: Select all
tags where appropriate when posting code. Read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]