Read a long time data structure but not how to use, in the Internet to see the data structure about PHP, learning a bit, and share with you.
Copy CodeThe code is as follows:
Class Hero
{
public $no;//Ranking
public $name;//Name
Public $next =null;//$next is a reference to an object instance that points to another hero
Public function __construct ($no = ", $name =")
{
$this->no= $no;
$this->name= $name;
}
static public Function showlist ($head)
{
$cur = $head;
while ($cur->next!=null)
{
echo "Rank:". $cur->next->no. ", Name:". $cur->next->name. "
";
$cur = $cur->next;
}
}
Normal insertion
static public Function Addhero ($head, $hero)
{
$cur = $head;
while ($cur->next!=null)
{
$cur = $cur->next;
}
$cur->next= $hero;
}
Orderly insertion of linked lists
static public Function addherosorted ($head, $hero)
{
$cur = $head;
$addNo = $hero->no;
while ($cur->next->no <= $addNo)
{
$cur = $cur->next;
}
/* $tep = new Hero ();
$tep = $cur->next;
$cur->next = $hero;
$hero->next = $tep; */
$hero->next= $cur->next;
$cur->next= $hero;
}
static public Function Deletehero ($head, $no)
{
$cur = $head;
while ($cur->next->no! = $no && $cur->next!= null)
{
$cur = $cur->next;
}
if ($cur->next->no! = null)
{
$cur->next = $cur->next->next;
echo "Delete succeeded
";
}
Else
{
echo "did not find
";
}
}
static public Function Updatehero ($head, $hero)
{
$cur = $head;
while ($cur->next->no! = $hero->no && $cur->next!= null)
{
$cur = $cur->next;
}
if ($cur->next->no! = null)
{
$hero->next = $cur->next->next;
$cur->next = $hero;
echo "changed successfully
";
}
Else
{
echo "did not find
";
}
}
}
Create Head Header
$head = new Hero ();
First one
$hero = new Hero (1, ' 111 ');
Connection
$head->next = $hero;
A second
$hero 2 = new Hero (3, ' 333 ');
Connection
Hero::addhero ($head, $hero 2);
$hero 3 = new Hero (2, ' 222 ');
Hero::addherosorted ($head, $hero 3);
Show
Hero::showlist ($head);
Delete
Hero::d Eletehero ($head, 4);
Show
Hero::showlist ($head);
Change
$hero 4=new Hero (2, ' xxx ');
Hero::updatehero ($head, $hero 4);
Show
Hero::showlist ($head);
Orderly insert words need to traverse through the list, the list of some knowledge does not introduce ha. Here is the main share of the code.
http://www.bkjia.com/PHPjc/781030.html www.bkjia.com true http://www.bkjia.com/PHPjc/781030.html techarticle read a long time data structure but not how to use, in the Internet to see the data structure about PHP, learning a bit, and share with you. Copy the code code as follows: Class He ...