如何在PHP项目中对单链表进行翻转?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
<?php
class Node{
private $value;
private $next;
public function __construct($value=null){
$this->value = $value;
}
public function getValue(){
return $this->value;
}
public function setValue($value){
$this->value = $value;
}
public function getNext(){
return $this->next;
}
public function setNext($next){
$this->next = $next;
}
}
//遍历,将当前节点的下一个节点缓存后更改当前节点指针
function reverse($head){
if($head == null){
return $head;
}
$pre = $head;//注意:对象的赋值
$cur = $head->getNext();
$next = null;
while($cur != null){
$next = $cur->getNext();
$cur->setNext($pre);
$pre = $cur;
$cur = $next;
}
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
$head->setNext(null);
$head = $pre;
return $head;
}
//递归,在反转当前节点之前先反转后续节点
function reverse2($head){
if (null == $head || null == $head->getNext()) {
return $head;
}
$reversedHead = reverse2($head->getNext());
$head->getNext()->setNext($head);
$head->setNext(null);
return $reversedHead;
}
function test(){
$head = new Node(0);
$tmp = null;
$cur = null;
// 构造一个长度为10的链表,保存头节点对象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();
?>
运行结果:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0
看完上述内容,你们掌握如何在PHP项目中对单链表进行翻转的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。