我正在尝试构建一个linkList。除了我的函数createLinkList
之外,一切正常。有一个if条件来指定它是否是第一个条目。我认为问题在于else
中的逻辑。任何人都可以停止发生什么事吗?
我希望我的示例中的输出类似于
object(createLinkList)#1 (1) {
["head"]=>
object(node)#2 (2) {
["data":"node":private]=>
string(4) "adam"
["link":"node":private]=>
object(node)#3 (2) {
["data":"node":private]=>
string(4) "andy"
["link":"node":private]=>
object(node)#4 (2) {
["data":"node":private]=>
string(4) "ben"
["link":"node":private]=>
}
//and so on...
}
}
}
相反,我得到了;
object(createLinkList)#1 (1) {
["head"]=>
object(node)#2 (2) {
["data":"node":private]=>
string(4) "adam"
["link":"node":private]=>
object(node)#3 (2) {
["data":"node":private]=>
string(4) "eric"
["link":"node":private]=>
*RECURSION*
}
}
}
这是我的代码,应该运行正常。非常感谢有人解释我做错了什么。感谢
。
$oLinkList = new createLinkList;
$oLinkList->createLinkList($aList);
echo "<pre>";
var_dump($oLinkList);
class createLinkList{
// // link to the first node
public $head;
// link to the last node
// public $tail;
// public $next;
//mutator method
public function __set($property, $value) {
$this->$property = $value;
}
//accessor method
public function __get($property) {
if (isset($this->$property)) {
return $this->$property;
} else {
return false;
}
}
// init the properties
function __construct() {
$this->head = null;
// $this->tail = null;
// $this->previous = null;
}
function createLinkList($aList){
if($aList == null || empty($aList)){
//$this = null;
return null;
}
$oPrevious;
foreach ($aList as $data) {
// create node/object
$link = new Node($data);
// first entry, have already created the node, so save a reference to in in the head var
if($this->head == null){
$this->head = $link;
$oPrevious = &$this->head;
}else{ // update the previous nodes link with a pointer to the node createds
$oPrevious->link = $link;
// $this->previous= $link;
$link->link = $this->head;
//$this->head = $link;
}
}
}
}// end class
class node{
private $data = null;
private $link;
//mutator method
public function __set($property, $value) {
$this->$property = $value;
}
//accessor method
public function __get($property) {
if (isset($this->$property)) {
return $this->$property;
} else {
return false;
}
}
/* Node constructor */
function __construct($data)
{
$this->data = $data;
$this->link = null;
}
}
答案 0 :(得分:1)
除非删除前一个元素,否则不应更新前一个元素。
您应该始终只存储第一个元素,并在需要时将其旁边的元素设置为新节点。
这应该通过一种方法处理,而不是预先处理。