phpは簡単な単一チェーンテーブルを実現する
3278 ワード
<?php
/**
* , data , id,
*/
// , data ,id value
class Node{
public $data;
public $next;
public function __construct($data,$next=null){
$this->data = $data;
$this->next = $next;
}
}
class Linklist{
public $header;
public function __construct(){
$this->header = new Node(null);
}
//
public function add(Node $node){
$current = $this->header;
while ($current->next !==null) {
$current = $current->next;
}
$current->next = $node;
}
// ,
public function show(){
$current = $this->header;
while ($current->next !== null){
//print_r($current->next->data);
//echo "<br/>";
echo $current->next->data['value'];
$current = $current->next;
}
}
// , ( )
public function getLength(){
$len = 0;
$current = $this->header;
while ($current->next !== null) {
$len++;
$current = $current->next;
}
return $len;
}
// value list , id, false
public function find($value){
$current = $this->header;
$flag = 0;
while ($current->next!==null){
if($value == $current->next->data['value']){
$flag = 1;
$id = $current->next->data['id'];
break;
}
$current = $current->next;
}
if($flag == 0){
return false;
}else{
return $id;
}
}
// , id
public function insert(Node $node,$id){
$current = $this->header;
while ($current->next!==null){
if($id == $current->next->data['id']){
$tmp = $current->next;
$current->next = $node;
$current->next->next = $tmp;
break;
}
$current = $current->next;
}
}
// ( )
public function del($id){
$current = $this->header;
while ($current->next!=null){
if($current->next->data['id'] == $id){
$current->next = $current->next->next;
break;
}
$current = $current->next;
}
}
// value
public function update($id,$value){
$current = $this->header;
while ($current->next !==null){
if($current->next->data['id'] == $id){
$current->next->data['value'] = $value;
}
$current = $current->next;
}
}
}
class Client{
public static function main(){
$list = new LinkList();
$data1 = array(
'id'=>1,
'value'=>'hello ',
);
$data2 = array(
'id'=>2,
'value'=>'world',
);
$data3 = array(
'id'=>3,
'value'=>'!',
);
$node1 = new Node($data1);
$node2 = new Node($data2);
$node3 = new Node($data3);
$list->add($node1);
$list->add($node2);
$list->add($node3);
// $list->show();
// echo "<br/>";
$node4 = new Node($data3);
$list->insert($node4, 2);
//$list->del(3);
$list->update(3, '!!!');
$list->show();
echo "<br/>";
}
}
Client::main();
?>
ノードの追加、ノードの削除、ノードの検索、ノードの変更、長さの取得は、遍歴で実現されます.