单链表反转

2020-08-25  本文已影响0人  淡淡de盐

单链表


单链表反转

function reversal()
{
    if ($this->size == 0) {
        return $this->header;
    }

    $pre     = null;
    $current = $this->header;
    while ($current != null) {
        $tmp = $current->next;

        $current->next = $pre;

        $pre = $current;

        $current = $tmp;
    }
    $this->header = $pre;

    return $this;
}

递归方法

public function reversRecursionNode($head)
{
    if ($head->next == null) {
        return $head;
    }
    $phead            = $this->reversRecursionNode($head->next);
    $head->next->next = $head;
    $head->next       = null;

    return $phead;
}
上一篇 下一篇

猜你喜欢

热点阅读