1.常见方法分为迭代和递归,迭代是从头到尾,递归是从尾到头
2.设置两个指针,old和new,每一项添加在new的后面,新链表头指针指向新的链表头
3.old->next不能直接指向new,而是应该设置一个临时指针tmp,指向old->next指向的地址空间,保存原链表数据,然后old->next指向new,new往前移动到old处new=old,最后old=tmp取回数据
while(old!=null){
tmp=old->next
old->next=new
new=old
old=tmp
}
<?php class Node{ public $data; public $next; } //头插法创建一个链表 $linkList=new Node(); $linkList->next=null;//头结点 for($i=1;$i<=10;$i++){ $node=new Node(); $node->data="aaa{$i}";//创建新结点$node $node->next=$linkList->next;//$node->next指向头结点->next $linkList->next=$node;//头结点->next指向$node } var_dump($linkList); function ReverseList($pHead){ $old=$pHead->next;//跳过头结点 $new=null; $tmp=null; //反转过程 while($old!=null){ $tmp=$old->next; $old->next=$new; $new=$old; $old=$tmp; } //给新链表加个头结点 $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 } } } } } } } } } } }