PHP如何将单链表翻转

墨辰丷
发布: 2018-05-16 17:36:56
原创
1485人浏览过

本篇文章主要介绍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;
}
//递归,在反转当前节点之前先反转后续节点 
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免费学习笔记(深入)”;

AIFreePhp企业建站系统
AIFreePhp企业建站系统

AiFreePhp(爱免费php企业建站程序是一个免费开源的PHP建站程序),基于PHP + MYSQL 与模板技术,具有产品展示,文章栏目,下载管理,友情链接等功能。无任何限制功能,程序简单实用,可用于中小企业网站建设,不收取任何费用。使用本程序,不可将程序变相转售,二次开发发布。 运行安装目/install/index.php一般要求安装在站点的根目录,不是根目录有试过有没有问题,请大家尽量以

AIFreePhp企业建站系统 0
查看详情 AIFreePhp企业建站系统

使用PHP实现单链表

PHP单链表的基本操作实例分享

JavaScript数据结构之单链表和循环链表实例分享

以上就是PHP如何将单链表翻转的详细内容,更多请关注php中文网其它相关文章!

相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号