<?php

namespace App\Server;

class Hero
{
    public $pre;
    public $no;
    public $name;
    public $next;

    public function __construct($no = '', $name = '')
    {
        $this->no   = $no;
        $this->name = $name;
    }

    public static function addHero($head, $hero)
    {
        $cur     = $head;
        $isExist = false;
        // 判断目前这个链表是否为空
        if (null == $cur->next) {
            $cur->next = $hero;
            $hero->pre = $cur;
        } else {
            // 如果不是空节点，则安排名来添加
            // 找到添加的位置

            while (null != $cur->next) {
                if ($cur->next->no > $hero->no) {
                    break;
                } elseif ($cur->next->no == $hero->no) {
                    $isExist = true;
                    echo '<br>不能添加相同的编号';
                }
                $cur = $cur->next;
            }
            if (!$isExist) {
                if (null != $cur->next) {
                    $hero->next = $cur->next;
                }
                $hero->pre = $cur;
                if (null != $cur->next) {
                    $hero->next->pre = $hero;
                }
                $cur->next = $hero;
            }
        }
    }

    // 遍历
    public static function showHero($head)
    {
        $cur = $head;
        while (null != $cur->next) {
            echo '<br>编号：' . $cur->next->no . '名字：' . $cur->next->name;
            $cur = $cur->next;
        }
    }

    public static function delHero($head, $herono)
    {
        $cur    = $head;
        $isFind = false;
        while (null != $cur) {
            if ($cur->no == $herono) {
                $isFind = true;
                break;
            }
            // 继续找
            $cur = $cur->next;
        }
        if ($isFind) {
            if (null != $cur->next) {
                $cur->next_pre = $cur->pre;
            }
            $cur->pre->next = $cur->next;
        } else {
            echo '<br>没有找到目标';
        }
    }
}
