看了很久数据结构但是没有怎么用过,在网上看到了关于PHP的数据结构,学习了一下,与大家一起分享一下。上一次分享了《undefinedPHP实现数据结构链表(普通插入,有序的链表的插入)》,这次来补充说一下双向链表。
001 | <?php |
002 | class Hero |
003 | { |
004 | public $pre =null; |
005 | public $no ; |
006 | public $name ; |
007 | public $next =null; |
008 | public function __construct( $no = '' , $name = '' ) |
009 | { |
010 | $this ->no= $no ; |
011 | $this ->name= $name ; |
012 | } |
013 | static public function addHero( $head , $hero ) |
014 | { |
015 | $cur = $head ; |
016 | $isExist =false; |
017 | //判断目前这个链表是否为空 |
018 | if ( $cur ->next==null) |
019 | { |
020 | $cur ->next= $hero ; |
021 | $hero ->pre= $cur ; |
022 | } |
023 | else |
024 | { |
025 | //如果不是空节点,则安排名来添加 |
026 | //找到添加的位置 |
027 | while ( $cur ->next!=null) |
028 | { |
029 | if ( $cur ->next->no > $hero ->no) |
030 | { |
031 | break ; |
032 | } |
033 | else if ( $cur ->next->no == $hero ->no) |
034 | { |
035 | $isExist =true; |
036 | echo " |
037 | 不能添加相同的编号"; |
038 | } |
039 | $cur = $cur ->next; |
040 | } |
041 | if (! $isExist ) |
042 | { |
043 | if ( $cur ->next!=null) |
044 | { |
045 | $hero ->next= $cur ->next; |
046 | } |
047 | $hero ->pre= $cur ; |
048 | if ( $cur ->next!=null) |
049 | { |
050 | $hero ->next->pre= $hero ; |
051 | } |
052 | $cur ->next= $hero ; |
053 | } |
054 | } |
055 | } |
056 | //遍历 |
057 | static public function showHero( $head ) |
058 | { |
059 | $cur = $head ; |
060 | while ( $cur ->next!=null) |
061 | { |
062 | echo " |
063 | 编号: ".$cur->next->no." 名字:". $cur ->next->name; |
064 | $cur = $cur ->next; |
065 | } |
066 | } |
067 | static public function delHero( $head , $herono ) |
068 | { |
069 | $cur = $head ; |
070 | $isFind =false; |
071 | while ( $cur !=null) |
072 | { |
073 | if ( $cur ->no== $herono ) |
074 | { |
075 | $isFind =true; |
076 | break ; |
077 | } |
078 | //继续找 |
079 | $cur = $cur ->next; |
080 | } |
081 | if ( $isFind ) |
082 | { |
083 | if ( $cur ->next!=null) |
084 | { |
085 | $cur ->next_pre= $cur ->pre; |
086 | } |
087 | $cur ->pre->next= $cur ->next; |
088 | } |
089 | else |
090 | { |
091 | echo " |
092 | 没有找到目标"; |
093 | } |
094 | } |
095 | } |
096 | $head = new Hero(); |
097 | $hero1 = new Hero(1, '1111' ); |
098 | $hero3 = new Hero(3, '3333' ); |
099 | $hero2 = new Hero(2, '2222' ); |
100 | Hero::addHero( $head , $hero1 ); |
101 | Hero::addHero( $head , $hero3 ); |
102 | Hero::addHero( $head , $hero2 ); |
103 | Hero::showHero( $head ); |
104 | Hero::delHero( $head ,2); |
105 | Hero::showHero( $head ); |
106 | ?> |