Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 反向链表的不同实现_Php_Data Structures_Linked List - Fatal编程技术网

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;

我在php中发现了几个反向链表实现,其中大多数都是相同的,但有一些小的区别,如:

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;    
    }
}

我说的对吗?

您的代码不起作用,原因有两个:

  • 您不需要测试空列表。该方法不考虑<代码> $$ ->第一个节点< /COD>是<代码> null < /C> >
  • 如果列表仅包含一个元素,则该方法不起作用
  • 如果列表包含两个或多个元素,则该方法仅反转列表的前两个元素,然后它陷入一个无休止的循环。这是因为在主体的最后一行中,当您使用
    $oldFirstNode
    的值更新
    $This->\u firstNode->next时,在下一次迭代中检查
    $This->\u firstNode->next!==NULL
    ,它不同于
    NULL
    ,因为它是
    $oldFirstNode
    的值,并且函数继续在这两个节点上循环
  • 对于像这样的算法,最好的方法是使用纸和笔,画出列表的元素和指向它们的变量,然后按照算法一步一步地更新它们

    最后请注意,如果一个算法总是用于某个基本任务,则很难找到一个新的、更有效的算法