Php does not have the Linked List data structure. You can use arrays to implement the data structure that has been viewed for a long time, but it has never been used. I saw the PHP Data Structure on the Internet and learned it, share with you.
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.