看了很久数据结构但是没有怎么用过,在网上看到了关于PHP的数据结构,学习了一下,与大家一起分享一下。
01 | class Hero |
02 | { |
03 | public $no ; //排名 |
04 | public $name ; //名字 |
05 | public $next =null; //$next是一个引用,指向另外一个Hero的对象实例 |
06 |
07 | public function __construct( $no = '' , $name = '' ) |
08 | { |
09 | $this ->no= $no ; |
10 | $this ->name= $name ; |
11 | } |
12 |
13 | static public function showList( $head ) |
14 | { |
15 | $cur = $head ; |
16 | while ( $cur ->next!=null) |
17 | { |
18 | echo "排名:" . $cur ->next->no. ",名字:" . $cur ->next->name." |
19 | "; |
20 | $cur = $cur ->next; |
21 | } |
22 | } |
23 | //普通插入 |
24 | static public function addHero( $head , $hero ) |
25 | { |
26 | $cur = $head ; |
27 | while ( $cur ->next!=null) |
28 | { |
29 | $cur = $cur ->next; |
30 | } |
31 | $cur ->next= $hero ; |
32 | } |
33 | //有序的链表的插入 |
34 | static public function addHeroSorted( $head , $hero ) |
35 | { |
36 | $cur = $head ; |
37 | $addNo = $hero ->no; |
38 | while ( $cur ->next->no <= $addNo ) |
39 | { |
40 | $cur = $cur ->next; |
41 | } |
42 | /*$tep = new Hero(); |
43 | $tep = $cur->next; |
44 | $cur->next = $hero; |
45 | $hero->next =$tep;*/ |
46 | $hero ->next= $cur ->next; |
47 | $cur ->next= $hero ; |
48 | } |
49 |
50 | static public function deleteHero( $head , $no ) |
51 | { |
52 | $cur = $head ; |
53 | while ( $cur ->next->no != $no && $cur ->next!= null) |
54 | { |
55 | $cur = $cur ->next; |
56 | } |
57 | if ( $cur ->next->no != null) |
58 | { |
59 | $cur ->next = $cur ->next->next; |
60 | echo "删除成功 |
61 | "; |
62 | } |
63 | else |
64 | { |
65 | echo "没有找到 |
66 | "; |
67 | } |
68 | } |
69 |
70 | static public function updateHero( $head , $hero ) |
71 | { |
72 | $cur = $head ; |
73 | while ( $cur ->next->no != $hero ->no && $cur ->next!= null) |
74 | { |
75 | $cur = $cur ->next; |
76 | } |
77 | if ( $cur ->next->no != null) |
78 | { |
79 | $hero ->next = $cur ->next->next; |
80 | $cur ->next = $hero ; |
81 | echo "更改成功 |
82 | "; |
83 | } |
84 | else |
85 | { |
86 | echo "没有找到 |
87 | "; |
88 | } |
89 | } |
90 | } |
01 | //创建head头 |
02 | $head = new Hero(); |
03 | //第一个 |
04 | $hero = new Hero(1, '111' ); |
05 | //连接 |
06 | $head ->next = $hero ; |
07 | //第二个 |
08 | $hero2 = new Hero(3, '333' ); |
09 | //连接 |
10 | Hero::addHero( $head , $hero2 ); |
11 | $hero3 = new Hero(2, '222' ); |
12 | Hero::addHeroSorted( $head , $hero3 ); |
13 | //显示 |
14 | Hero::showlist( $head ); |
15 | //删除 |
16 | Hero::deleteHero( $head ,4); |
17 | //显示 |
18 | Hero::showlist( $head ); |
19 | //更改 |
20 | $hero4 = new Hero(2, 'xxx' ); |
21 | Hero::updateHero( $head , $hero4 ); |
22 | //显示 |
23 | Hero::showlist( $head ); |
有序的插入的话需要遍历一遍链表,链表的一些知识就不介绍了哈。这里主要分享一下代码。