mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-07-09 19:16:19 +02:00
29 lines
633 B
PHP
29 lines
633 B
PHP
<?php
|
|
|
|
namespace DataStructures\ReverseLinkedList;
|
|
|
|
/**
|
|
* Reverse linked list
|
|
* (https://en.wikipedia.org/wiki/Linked_list).
|
|
*
|
|
* @author Michał Żarnecki https://github.com/rzarno
|
|
*/
|
|
class ReverseLinkedList
|
|
{
|
|
public function reverse(LinkedListItem $item): LinkedListItem
|
|
{
|
|
$next = $item->getNext();
|
|
$item->setNext(null);
|
|
while (true) {
|
|
$item->setPrev($next);
|
|
if (! $next) {
|
|
return $item;
|
|
}
|
|
$nextNext = $next->getNext();
|
|
$next->setNext($item);
|
|
$item = $next;
|
|
$next = $nextNext;
|
|
}
|
|
}
|
|
}
|