PHP反向链表
方法一:迭代
function reverseList($head) {
//第一种方法
$h = $head;//移动节点(后一个节点)
$n = null;//存储节点(前一个节点)
while($h != null){
$temp = $h->next; //存储 移动节点的指针(下一个节点的地址)
$h->next = $n;//移动节点的指针指向存储节点
$n = $h;//存储节点获得移动节点的地址
$h = $temp;//移动节点向后移动
}
return $n;
//第二种方法
$h = $head;
$n = $head -> next;
$head -> next = null;
while($n != null){
$temp = $n -> next; //存储后一个节点的地址
$n -> next = $h;//后一个节点的指针指向前面的节点
$h = $n;//前一个节点开始向后推
$n = $temp;//后一个节点开始向后推
}
return $h;
}
方法二:递归
function reverseList($head) {
if($head == null || $head -> next == null){
return $head;
}
$p = reverseList($head ->next );
$head->next->next = $head;
$head -> next = null;
return $p;
}