Php 反向链表的不同实现
我在php中发现了几个反向链表实现,其中大多数都是相同的,但有一些小的区别,如:Php 反向链表的不同实现,php,data-structures,linked-list,Php,Data Structures,Linked List,我在php中发现了几个反向链表实现,其中大多数都是相同的,但有一些小的区别,如: public function reverse() { if ( $this->_firstNode !== NULL ) { if ( $this->_firstNode->next !== NULL ) { $reversed = $temp = NULL; $current = $this->_firstNode;
public function reverse() {
if ( $this->_firstNode !== NULL ) {
if ( $this->_firstNode->next !== NULL ) {
$reversed = $temp = NULL;
$current = $this->_firstNode;
while ( $current !== NULL ) {
$temp = $current->next;
$current->next = $reversed;
$reversed = $current;
$current = $temp;
}
$this->_firstNode = $reversed;
}
}
}
但我认为可以改为:
public function reverse() {
while ( $this->_firstNode->next !== NULL ) {
$oldFirstNode = $this->_firstNode;
$this->_firstNode = $oldFirstNode->next;
$oldFirstNode->next = NULL;
$this->_firstNode->next = $oldFirstNode;
}
}
我说的对吗?您的代码不起作用,原因有两个:
$oldFirstNode
的值更新$This->\u firstNode->next时,在下一次迭代中检查$This->\u firstNode->next!==NULL
,它不同于NULL
,因为它是$oldFirstNode
的值,并且函数继续在这两个节点上循环