PHP small tutorial implementation linked list. I have read the data structure for a long time, but I have never used it. I have read the data structure of PHP on the Internet and shared it with you. Copy the code as follows: classHe has been reading the data structure for a long time but has never been used. she saw the data structure about PHP on the Internet, learned about it, and shared it with everyone.
The code is as follows:
Class Hero
{
Public $ no; // ranking
Public $ name; // name
Public $ next = null; // $ next is a reference pointing to another Hero object instance.
Public function _ construct ($ no = '', $ name = '')
{
$ This-> no = $ no;
$ This-> name = $ name;
}
Static public function showList ($ head)
{
$ Cur = $ head;
While ($ cur-> next! = Null)
{
Echo "ranking:". $ cur-> next-> no. ", name:". $ cur-> next-> name ."
";
$ Cur = $ cur-> next;
}
}
// Normal insert
Static public function addHero ($ head, $ hero)
{
$ Cur = $ head;
While ($ cur-> next! = Null)
{
$ Cur = $ cur-> next;
}
$ Cur-> next = $ hero;
}
// Insert an ordered linked list
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;
Echo "deleted successfully
";
}
Else
{
Echo "not found
";
}
}
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;
$ Cur-> next = $ hero;
Echo "changed
";
}
Else
{
Echo "not found
";
}
}
}
// Create a head header
$ Head = new Hero ();
// The first
$ Hero = new Hero (1, '20140901 ');
// Connection
$ Head-> next = $ hero;
// Second
$ Hero2 = new Hero (3, '20140901 ');
// Connection
Hero: addHero ($ head, $ hero2 );
$ Hero3 = new Hero (2, '20140901 ');
Hero: addHeroSorted ($ head, $ hero3 );
// Display
Hero: showlist ($ head );
// Delete
Hero: deleteHero ($ head, 4 );
// Display
Hero: showlist ($ head );
// Change
$ Hero4 = new Hero (2, 'XXX ');
Hero: updateHero ($ head, $ hero4 );
// Display
Hero: showlist ($ head );
For ordered inserts, you need to traverse the linked list. the knowledge of the linked list is not introduced. Here we will mainly share the code.
Bytes. The code is as follows: class He...