当前位置:Gxlcms > php框架 > PHP单链表的实现代码

PHP单链表的实现代码

时间:2021-07-01 10:21:17 帮助过:62人阅读

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。

单链表简介

链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。

关键代码如下所示:

  1. <?php
  2. /**
  3. * 单链表
  4. */
  5. class Demo
  6. {
  7. private $id;
  8. public $name;
  9. public $next;
  10. public function __construct ($id = '', $name = '')
  11. {
  12. $this->id = $id;
  13. $this->name = $name;
  14. }
  15. static public function show ($head)
  16. {
  17. $cur = $head;
  18. while ($cur->next) {
  19. echo $cur->next->id,'###',$cur->next->name,'<br />';
  20. $cur = $cur->next;
  21. }
  22. echo '<hr />';
  23. }
  24. //尾插法
  25. static public function push ($head, $node)
  26. {
  27. $cur = $head;
  28. while (NULL != $cur->next) {
  29. $cur = $cur->next;
  30. }
  31. $cur->next = $node;
  32. return $head;
  33. }
  34. static public function insert($head, $node)
  35. {
  36. $cur = $head;
  37. while (NULL != $cur->next) {
  38. if ($cur->next->id > $node->id) {
  39. break;
  40. }
  41. $cur = $cur->next;
  42. }
  43. $node->next = $cur->next;
  44. $cur->next = $node;
  45. return $head;
  46. }
  47. static public function edit($head, $node)
  48. {
  49. $cur = $head;
  50. while (NULL != $cur->next) {
  51. if ($cur->next->id == $node->id) {
  52. break;
  53. }
  54. $cur = $cur->next;
  55. }
  56. $cur->next->name = $node->name;
  57. return $head;
  58. }
  59. static public function pop ($head, $node)
  60. {
  61. $cur = $head;
  62. while (NULL != $cur->next) {
  63. if ($cur->next == $node) {
  64. break;
  65. }
  66. $cur = $cur->next;
  67. }
  68. $cur->next = $node->next;
  69. return $head;
  70. }
  71. }
  72. $team = new Demo();
  73. $node1 = new Demo(1, '唐三藏');
  74. Demo::push($team, $node1);
  75. $node1->name = '唐僧';
  76. Demo::show($team);
  77. // Demo::show($team);
  78. $node2 = new Demo(2, '孙悟空');
  79. Demo::insert($team, $node2);
  80. // Demo::show($team);
  81. $node3 = new Demo(5, '白龙马');
  82. Demo::push($team, $node3);
  83. // Demo::show($team);
  84. $node4 = new Demo(3, '猪八戒');
  85. Demo::insert($team, $node4);
  86. // Demo::show($team);
  87. $node5 = new Demo(4, '沙和尚');
  88. Demo::insert($team, $node5);
  89. // Demo::show($team);
  90. $node4->name = '猪悟能';//php对象传引用,所以Demo::edit没有必要
  91. // unset($node4);
  92. // $node4 = new Demo(3, '猪悟能');
  93. // Demo::edit($team, $node4);
  94. Demo::pop($team, $node1);
  95. Demo::show($team);

以上所述是小编给大家介绍的PHP单链表的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行