This article mainly introduces the PHP implementation of single-linked list rollover operation, combined with instance form analysis of the PHP single linked list of the definition, traversal, recursion, flip and other related operations skills, the need for friends can refer to the next
The example in this paper is about the single-linked list rollover operation implemented by PHP. Share to everyone for your reference, as follows:
When a sequence contains only a link to its successor, it is called a single-linked list.
Here is a definition of a single-linked list and how to flip it:
<?php/** * @file reverselink.php * @author Showersun * @date 2016/03/01 10:33:25 **/class node{private $value; Private $next; Public function __construct ($value =null) {$this->value = $value; } public Function GetValue () {return $this->value; The Public Function SetValue ($value) {$this->value = $value; } public Function GetNext () {return $this->next; The Public Function Setnext ($next) {$this->next = $next; }}//iterates over the current node after the next node is cached and changes the current node pointer function reverse ($head) {if ($head = = null) {return $head; } $pre = $head;//Note: The assignment of the object $cur = $head->getnext (); $next = null; while ($cur! = null) {$next = $cur->getnext (); $cur->setnext ($pre); $pre = $cur; $cur = $next; }//Set the next node of the original list's head node to NULL, then assign the inverted head node to head $head->setnext (null); $head = $pre; return $head;} Recursively reverses the subsequent node function Reverse2 ($head) {if (null = = $head | | null = = $head->getnext ()) {return $head, before reversing the current node; } $reversedHead = Reverse2 ($head->getnext ()); $hEad->getnext ()->setnext ($head); $head->setnext (NULL); return $reversedHead;} function test () {$head = new Node (0); $tmp = null; $cur = null; Construct a linked list of length 10, Save the head node object head for ($i =1; $i <10; $i + +) {$tmp = new node ($i); if ($i = = 1) {$head->setnext ($tmp); }else{$cur->setnext ($tmp); } $cur = $tmp; }//print_r ($head); exit; $tmpHead = $head; while ($tmpHead! = null) {echo $tmpHead->getvalue (). ' '; $tmpHead = $tmpHead->getnext (); } echo "\ n"; $head = reverse ($head); $head = Reverse2 ($head); while ($head! = null) {echo $head->getvalue (). ' '; $head = $head->getnext (); }}test ();? >
Operation Result:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0
Articles you may be interested in:
PHP implementation of merging two ordered arrays of methods explained
A detailed approach to the implementation of the Joseph ring problem in PHP
The method of using Passport to realize auth certification in Laravel5.5