PHP实现单链表翻转操作示例
本文实例讲述了PHP实现单链表翻转操作。分享给大家供大家参考,具体如下:
当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。
这里给出了一个单链表的定义及翻转操作方法:
value=$value; } publicfunctiongetValue(){ return$this->value; } publicfunctionsetValue($value){ $this->value=$value; } publicfunctiongetNext(){ return$this->next; } publicfunctionsetNext($next){ $this->next=$next; } } //遍历,将当前节点的下一个节点缓存后更改当前节点指针 functionreverse($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; } //递归,在反转当前节点之前先反转后续节点 functionreverse2($head){ if(null==$head||null==$head->getNext()){ return$head; } $reversedHead=reverse2($head->getNext()); $head->getNext()->setNext($head); $head->setNext(null); return$reversedHead; } functiontest(){ $head=newNode(0); $tmp=null; $cur=null; //构造一个长度为10的链表,保存头节点对象head for($i=1;$i<10;$i++){ $tmp=newNode($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(); ?>
运行结果:
01234567899876543210
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》
希望本文所述对大家PHP程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。