我正在创建一个链表类,并且对对象的引用有一些混淆。
根据我的理解,默认情况下,对象是通过引用复制的$Obj1=$Obj2$Obj1是$Obj2的别名。
有人能指出链接列表实现中哪一个是正确的吗。
$firstNode->next = $this->first;---> seems to be correct
or
$firstNode->next =& $this->first;
$this->first = $firstNode;-----> seems to be correct as $firstNode is an object
or
$this->first = & $firstNode;
代码:
class Node {
public $element;
public $next;
public function __construct($element){
$this->element = $element;
$this->next = NULL;
}
}
class Linklist {
private $first;
private $listSize;
public function __construct(){
$this->first = NULL;
$this->listSize = 0;
}
public function InsertToFirst($element){
$firstNode = new Node($element);
$firstNode->next = $this->first; // or $firstNode->next =& $this->first;
$this->first = $firstNode; // or $this->first = & $firstNode;
}
在PHP中,如果每个节点本身都是对象,并且next
和first
也是该节点类型的对象,则不需要对链表使用引用赋值(别名/&
)。
请参阅PHP手册中的对象和引用以了解详细信息。