Hero.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Server;
  3. class Hero
  4. {
  5. public $pre;
  6. public $no;
  7. public $name;
  8. public $next;
  9. public function __construct($no = '', $name = '')
  10. {
  11. $this->no = $no;
  12. $this->name = $name;
  13. }
  14. public static function addHero($head, $hero)
  15. {
  16. $cur = $head;
  17. $isExist = false;
  18. // 判断目前这个链表是否为空
  19. if (null == $cur->next) {
  20. $cur->next = $hero;
  21. $hero->pre = $cur;
  22. } else {
  23. // 如果不是空节点,则安排名来添加
  24. // 找到添加的位置
  25. while (null != $cur->next) {
  26. if ($cur->next->no > $hero->no) {
  27. break;
  28. } elseif ($cur->next->no == $hero->no) {
  29. $isExist = true;
  30. echo '<br>不能添加相同的编号';
  31. }
  32. $cur = $cur->next;
  33. }
  34. if (!$isExist) {
  35. if (null != $cur->next) {
  36. $hero->next = $cur->next;
  37. }
  38. $hero->pre = $cur;
  39. if (null != $cur->next) {
  40. $hero->next->pre = $hero;
  41. }
  42. $cur->next = $hero;
  43. }
  44. }
  45. }
  46. // 遍历
  47. public static function showHero($head)
  48. {
  49. $cur = $head;
  50. while (null != $cur->next) {
  51. echo '<br>编号:' . $cur->next->no . '名字:' . $cur->next->name;
  52. $cur = $cur->next;
  53. }
  54. }
  55. public static function delHero($head, $herono)
  56. {
  57. $cur = $head;
  58. $isFind = false;
  59. while (null != $cur) {
  60. if ($cur->no == $herono) {
  61. $isFind = true;
  62. break;
  63. }
  64. // 继续找
  65. $cur = $cur->next;
  66. }
  67. if ($isFind) {
  68. if (null != $cur->next) {
  69. $cur->next_pre = $cur->pre;
  70. }
  71. $cur->pre->next = $cur->next;
  72. } else {
  73. echo '<br>没有找到目标';
  74. }
  75. }
  76. }