1. Common methods are divided into iteration and recursion. Iteration is from the beginning to the end, and recursion is from the end to the end
2. Set two pointers, old and new. Each item is added after new, and the new chain header pointer points to the new chain header
3. Old - > next cannot point directly to new, but a temporary pointer tmp should be set to point to the address space pointed to by old - > next, save the original linked list data, then old - > next points to new,new moves forward to old, new=old, and finally old=tmp retrieves the data
while(old!=null){
tmp=old->next
old->next=new
new=old
old=tmp
}
<?php class Node{ public $data; public $next; } //Creating a linked list by head insertion $linkList=new Node(); $linkList->next=null;//Head node for($i=1;$i<=10;$i++){ $node=new Node(); $node->data="aaa{$i}";//Create a new node $node $node->next=$linkList->next;//$node->next Pointing head node->next $linkList->next=$node;//Head node->next point $node } var_dump($linkList); function ReverseList($pHead){ $old=$pHead->next;//Jump over node $new=null; $tmp=null; //Reversal process while($old!=null){ $tmp=$old->next; $old->next=$new; $new=$old; $old=$tmp; } //Add a header node to the new list $newHead=new Node(); $newHead->next=$new; var_dump($newHead); } ReverseList($linkList);
object(Node)#1 (2) { ["data"]=> NULL ["next"]=> object(Node)#11 (2) { ["data"]=> string(5) "aaa10" ["next"]=> object(Node)#10 (2) { ["data"]=> string(4) "aaa9" ["next"]=> object(Node)#9 (2) { ["data"]=> string(4) "aaa8" ["next"]=> object(Node)#8 (2) { ["data"]=> string(4) "aaa7" ["next"]=> object(Node)#7 (2) { ["data"]=> string(4) "aaa6" ["next"]=> object(Node)#6 (2) { ["data"]=> string(4) "aaa5" ["next"]=> object(Node)#5 (2) { ["data"]=> string(4) "aaa4" ["next"]=> object(Node)#4 (2) { ["data"]=> string(4) "aaa3" ["next"]=> object(Node)#3 (2) { ["data"]=> string(4) "aaa2" ["next"]=> object(Node)#2 (2) { ["data"]=> string(4) "aaa1" ["next"]=> NULL } } } } } } } } } } } object(Node)#12 (2) { ["data"]=> NULL ["next"]=> object(Node)#2 (2) { ["data"]=> string(4) "aaa1" ["next"]=> object(Node)#3 (2) { ["data"]=> string(4) "aaa2" ["next"]=> object(Node)#4 (2) { ["data"]=> string(4) "aaa3" ["next"]=> object(Node)#5 (2) { ["data"]=> string(4) "aaa4" ["next"]=> object(Node)#6 (2) { ["data"]=> string(4) "aaa5" ["next"]=> object(Node)#7 (2) { ["data"]=> string(4) "aaa6" ["next"]=> object(Node)#8 (2) { ["data"]=> string(4) "aaa7" ["next"]=> object(Node)#9 (2) { ["data"]=> string(4) "aaa8" ["next"]=> object(Node)#10 (2) { ["data"]=> string(4) "aaa9" ["next"]=> object(Node)#11 (2) { ["data"]=> string(5) "aaa10" ["next"]=> NULL } } } } } } } } } } }