Learn PHP, learn the grammar, start to try to implement the data structure, the realization of the single-linked list today
<?php class Node//node data structure {public $id; Public $name; Public $next; Public function __construct ($id, $name)//constructor {$this->id= $id; $this->name= $name; $this->next=null; }} class Linklist//linked list data structure {private $header; Public function __construct ()//list constructor {$this->header=new node ($id =null, $name =null); The Public function Add ($node)//function {$current = $this->header; To add a node to the list while ($current->next!=null) {if ($current->id> $node->id) break; else if ($current->next== $node->id) {exit (' already exist! '); } $current = $current->next; } $node->next= $current->next; $current->next= $node; } Public Function del ($id)Deleting a node in a linked list {$current = $this->header; $flag =false; while ($current->next!=null) {if ($current->next->id== $id) { $flag =true; Break } $current = $current->next; if ($flag) $current->next= $current->next->next; else echo "Can not find the node which id=". $id; } public Function GetLength ()//Gets the length of the linked list {$current = $this->header; $i = 0; while ($current->next!=null) {$i + +; $current = $current->next; } return $i; } public Function GetList ()//Gets the entire list {$current = $this->header; if ($current->next==null) {echo "Empty list"; Empty table return; } while ($current->next!=null) {echo "id=". $current->next->id. ",". " Name= ". $current->next->name." <br> "; if ($current->next->next==null) break; $current = $current->next; }} Public Function Update ($id, $name)//Update table {$current = $this->header; if ($current->next==null) exit ("Empty list"); while ($current->next!=null) {if ($current->id== $id) break; $current = $current->next; } return $current->name= $name; }} $list =new linklist (); Constructs a table $list->add (new node (1, ' AAA ')); $list->add (New node (2, ' BBB ')); $list->add (New node (3, ' CCC ')); $list->add (New node (4, ' ddd ')); $list->add (New node (5, ' Eee ')); $list->add (new node (6, ' FFF ')); $list->add (new node (7, ' GGG ')); $liSt->add (new node (8, ' hhh ')); $list->add (new node (9, ' III ')); $list->getlist (); echo "<br/> the length is". $list->getlength (). " <br/> "; echo "Test delete node <br/>"; $list->del (' 8 '); $list->getlist (); echo "Test update node <br/>"; $list->update (' 9 ', ' AAA '); $list->getlist ();? >
The output is:
Id=1, Name=aaa id=2, name=bbb id=3, NAME=CCC id=4, name=ddd id=5, name=eee id=6, Name=fff id=7, name=ggg id=8, name=hhh id=9, name=iii the length is 9 test Delete node I D=1, Name=aaa id=2, name=bbb id=3, NAME=CCC id=4, name=ddd id=5, name=eee id=6, Name=fff id=7 , Name=ggg id=9, NAME=III Test update node id=1, name=aaa id=2, name=bbb id=3, NAME=CCC id=4, name=ddd id=5 , Name=eee id=6, Name=fff id=7, Name=ggg id=9, NAME=AAA