Hero.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Server;
  3. class Hero
  4. {
  5. public $pre = null;
  6. public $no;
  7. public $name;
  8. public $next = null;
  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 ($cur->next == null) {
  20. $cur->next = $hero;
  21. $hero->pre = $cur;
  22. } else {
  23. //如果不是空节点,则安排名来添加
  24. //找到添加的位置
  25. while ($cur->next != null) {
  26. if ($cur->next->no > $hero->no) {
  27. break;
  28. } else if ($cur->next->no == $hero->no) {
  29. $isExist = true;
  30. echo "<br>不能添加相同的编号";
  31. }
  32. $cur = $cur->next;
  33. }
  34. if (!$isExist) {
  35. if ($cur->next != null) {
  36. $hero->next = $cur->next;
  37. }
  38. $hero->pre = $cur;
  39. if ($cur->next != null) {
  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 ($cur->next != null) {
  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 ($cur != null) {
  60. if ($cur->no == $herono) {
  61. $isFind = true;
  62. break;
  63. }
  64. //继续找
  65. $cur = $cur->next;
  66. }
  67. if ($isFind) {
  68. if ($cur->next != null) {
  69. $cur->next_pre = $cur->pre;
  70. }
  71. $cur->pre->next = $cur->next;
  72. } else {
  73. echo "<br>没有找到目标";
  74. }
  75. }
  76. }