A two-way linked list is also called a double-chain table, which is a type of linked list. each of its data nodes has two pointers pointing to the direct successor and direct precursor respectively. Therefore, starting from any node in the two-way linked list, you can easily access its precursor node and successor node. Generally, we have constructed a dual-view data structure for a long time, but we have never used it any more. I saw the data structure of PHP on the Internet, learned it, and shared it with you. The last time I shared the PHP small tutorial implementation linked list, this time I will add a two-way linked list.
The code is as follows:
Class Hero
{
Public $ pre = null;
Public $ no;
Public $ name;
Public $ next = null;
Public function _ construct ($ no = '', $ name = '')
{
$ This-> no = $ no;
$ This-> name = $ name;
}
Static public function addHero ($ head, $ hero)
{
$ Cur = $ head;
$ IsExist = false;
// Determine whether the linked list is empty
If ($ cur-> next = null)
{
$ Cur-> next = $ hero;
$ Hero-> pre = $ cur;
}
Else
{
// If it is not an empty node, add the security ranking.
// Locate the added location
While ($ cur-> next! = Null)
{
If ($ cur-> next-> no> $ hero-> no)
{
Break;
}
Else if ($ cur-> next-> no ==$ hero-> no)
{
$ IsExist = true;
Echo"
The same number cannot be added ";
}
$ Cur = $ cur-> next;
}
If (! $ IsExist)
{
If ($ cur-> next! = Null)
{
$ Hero-> next = $ cur-> next;
}
$ Hero-> pre = $ cur;
If ($ cur-> next! = Null)
{
$ Hero-> next-> pre = $ hero;
}
$ Cur-> next = $ hero;
}
}
}
// Traverse
Static public function showHero ($ head)
{
$ Cur = $ head;
While ($ cur-> next! = Null)
{
Echo"
No.: ". $ cur-> next-> no." name: ". $ cur-> next-> name;
$ Cur = $ cur-> next;
}
}
Static public function delHero ($ head, $ herono)
{
$ Cur = $ head;
$ IsFind = false;
While ($ cur! = Null)
{
If ($ cur-> no ==$ herono)
{
$ IsFind = true;
Break;
}
// Continue searching
$ Cur = $ cur-> next;
}
If ($ isFind)
{
If ($ cur-> next! = Null)
{
$ Cur-> next_pre = $ cur-> pre;
}
$ Cur-> pre-> next = $ cur-> next;
}
Else
{
Echo"
No target found ";
}
}
}
$ Head = new Hero ();
$ Hero1 = new Hero (1, '20140901 ');
$ Hero3 = new Hero (3, '20140901 ');
$ Hero2 = new Hero (2, '20140901 ');
Hero: addHero ($ head, $ hero1 );
Hero: addHero ($ head, $ hero3 );
Hero: addHero ($ head, $ hero2 );
Hero: showHero ($ head );
Hero: delHero ($ head, 2 );
Hero: showHero ($ head );
?>