• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP实现单链表翻转操作示例

php 搞代码 4年前 (2022-01-22) 12次浏览 已收录 0个评论

当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。本文主要介绍了PHP实现单链表翻转操作,结合实例形式分析了php单链表的定义、遍历、递归、翻转等相关操作技巧,需要的朋友可以参考下,希望能帮助到大家。

这里给出了一个单链表的定义及翻转操作方法:

<?php/** * @file reverseLink.php * @author showersun * @date 2016/03/01 10:33:25 **/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;}//递归<a>2本文来源gao*daima.com搞@代#码&网6</a><pre>搞gaodaima代码

,在反转当前节点之前先反转后续节点 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

相关推荐:
python实现单链表

PHP单链表翻转

php代码 PHP单链表的实现代码

以上就是PHP实现单链表翻转操作示例的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP实现单链表翻转操作示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址