PHP-几行代码翻转链表

翻转链表

声明结构

class node
{
    public $val;
    public $next;

    public function __construct($val)
    {
        $this->val = $val;
    }
}


$head                   = new node(1);
$head->next             = new node(2);
$head->next->next       = new node(3);
$head->next->next->next = new node(4);

输出

node Object
(
    [val] => 1
    [next] => node Object
        (
            [val] => 2
            [next] => node Object
                (
                    [val] => 3
                    [next] => node Object
                        (
                            [val] => 4
                            [next] => 
                        )

                )

        )

)

第一种翻转方式 (递归)

function reNode($head)
{
   if (!$head->next) {
       return $head;
   }

   $prevNode         = reNode($head->next);
   $head->next->next = $head;
   $head->next       = null;

   return $prevNode;
}

print_r(reNode($head));

第二种翻转方式 (循环)

function reNode($head) {
    while ($head) {
        $tmpNode    = $head->next;
        $head->next = empty($newHead) ? null : $newHead;
        $newHead    = $head;
        $head       = $tmpNode;
    }
    return $newHead;
}

print_r(reNode($head));

输出

node Object
(
    [val] => 4
    [next] => node Object
        (
            [val] => 3
            [next] => node Object
                (
                    [val] => 2
                    [next] => node Object
                        (
                            [val] => 1
                            [next] => 
                        )

                )

        )

)

你可能感兴趣的:(PHP-几行代码翻转链表)