PHP实现单链表翻转操纵示例
发布时间:2021-03-31 18:04:52 所属栏目:编程 来源:网络整理
导读:本篇章节讲授PHP实现单链表翻转操纵。分享给各人供各人参考,详细如下: 当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。 这里给出了一个单链表的界说及翻转操纵要领: value = $value; } public function getValue(){ return $this->v
本篇章节讲授PHP实现单链表翻转操纵。分享给各人供各人参考,详细如下: 当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。 这里给出了一个单链表的界说及翻转操纵要领: 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();
?>
运行功效: 更多关于PHP相干内容感乐趣的读者可查察本站专题:《》、《》、《》、《》、《》及《》 但愿本文所述对各人PHP措施计划有所辅佐。 (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |