博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP 逆转单链表
阅读量:7055 次
发布时间:2019-06-28

本文共 1566 字,大约阅读时间需要 5 分钟。

1 
next指向自己,将自己的next指向null10 #为了获得逆转后的头结点,在最后一个非空节点,即cnode->next == null时,将节点返回11 function reverse_list_r($node) {12 if ($node->next == null) {13 return $node;14 } else {15 $head = reverse_list_r($node->next);16 $node->next->next = $node;17 $node->next = null;18 return $head;19 }20 }21 22 #非递归版本23 #思想是需要保存下三个节点,分别是cnode,next(cnode->next),next2(cnode->next->next)24 #每次要执行的操作只有将next->next指向cnode,然后依次将这三个节点后移,直到next == null25 function reverse_list($head) {26 $cnode = $head;27 $next = $head->next;28 $head->next = null;29 while ($next != null) {30 $next2 = $next->next;31 $next->next = $cnode; 32 $cnode = $next;33 $next = $next2;34 }35 36 return $cnode;37 }38 39 #遍历单链表40 function traverse($head) {41 $cnode = $head;42 while ($cnode != null) {43 echo $cnode->data . " ";44 $cnode = $cnode->next;45 }46 echo "
";47 }48 49 $head = new Node();50 $n1 = new Node();51 $n2 = new Node();52 $n3 = new Node();53 $head->data = 0;54 $n1->data = 1;55 $n2->data = 2;56 $n3->data = 3;57 $head->next = $n1;58 $n1->next = $n2;59 $n2->next = $n3;60 $n3->next = null;61 traverse($head);62 63 $rhead = reverse_list_r($head);64 traverse($rhead);65 66 $rrhead = reverse_list($rhead);67 traverse($rrhead);68 ?>

0 1 2 3 

3 2 1 0 
0 1 2 3

转载地址:http://utool.baihongyu.com/

你可能感兴趣的文章
notepad把某个字母或者标定符号后面的内容全部删除
查看>>
KVO VS isa
查看>>
windows MSOCache删除
查看>>
【C#】C#线程_混合线程的同步构造
查看>>
install lsa package for R on ubuntu 10.04 lts lucid
查看>>
英文单词缩写查询
查看>>
由网页下载程序(完美下载图片、js、css、修改网页)解析三大网页难题
查看>>
[转载]c#委托事件简单例子
查看>>
Lua脚本语法说明(修订) - 沐枫 - 博客园
查看>>
【My Project】织物疵点检测机器视觉系统 软件测试平台
查看>>
程序3
查看>>
HDOJ---1267 下沙的沙子2[DP或卡特兰数]
查看>>
love2d教程26--对话条
查看>>
每日英语:Luxury-Goods Companies Go to Great Lengths for China's VIP Shoppers
查看>>
资源推荐 五个常用MySQL图形化管理工具
查看>>
IBM MQ 2035 或 2013认证错误的解决方法
查看>>
C++ MFC界面读写USB HID设备数据程序
查看>>
Windows Phone8开发工具包简述(转载)
查看>>
Android——程序移植 相关知识总结贴
查看>>
sql字符串的拼接 (字符串和二进制,erlang的mysql驱动)
查看>>