* Refer to PHP standard library design interface
http://php.net/manual/en/class.spldoublylinkedlist.php
* Reverse one-way linked list
Reverse methods, other methods for the convenience of testing
<?php/** * Created by Phpstorm. * USER:MCH * DATE:8/11/18 * time:00:25 */class Node {public $value; Public $next; Public function __construct ($data) {$this->value = $data; $this->next = null; }} class LinkedList implements Iterator, countable {private $head; Private $cur; Public Function __construct () {$this->head = $this->cur = null; } public Function IsEmpty () {return is_null ($this->head); Public function count () {$p = $this->head; $count = 0; while ($p!== null) {$p = $p->next; $count + +; } return $count; Public function current () {if ($this->isempty ()) {return null; } return $this->cur->value; Public function Next () {if (Is_null ($this->cur)) {return null; } $this->cur = $this->cur->next; } Public Function Rewind () { $this->cur = $this->head; } public Function valid () {return!is_null ($this->cur); Public Function key () {$p = $this->head; $key = 0; while ($p!== $this->cur) {$p = $p->next; $key + +; } return $key; The public function push ($value) {if ($this->isempty ()) {$this->head = new Node ($value); $this->cur = $this->head; } else {$this->cur = $this->head; while ($this->cur->next!== null) {$this->cur = $this->cur->next; } $this->cur->next = new Node ($value); } return $this; The Public function ForEach (callable $callback, mixed $userdata = null) {$this->rewind (); while ($this->valid ()) {Call_user_func ($callback, $this->current (), $this->key (), $userdata); $this->next (); } } Public Function reverse () {if ($this->isempty ()) return; if ($this->count () < 2) return; $prev = null; $cur = $this->head; while ($cur) {//save next $next = $cur->next; Move cur to head $this->head = $cur; $cur->next = $prev; Iterate $prev = $cur; $cur = $next; } } }
* Test
$list = new LinkedList (); for ($i = N, $i <, $i + +) { $list->push (Chr ($i)),} $list->foreach (function ($value, $index) { printf (" [%d] =%s<br/> ", $index, $value);}); Echo '-------------------<br/> '; $list->reverse (); $list->foreach (function ($value, $index) { printf ("[%d] =%s<br/>", $index, $value);});
* Output:
[0] = A
[1] = B
[2] = C
[3] = D
[4] = = E
[5] = F
....
-------------------
[0] = Z
[1] = Y
[2] = X
[3] = W
[4] = V
[5] = = U
...
PHP Unidirectional list reversal reverse (no empty head node)