class Singlelist{
private $head;
private $size;
public function __construct(){
$this->head = null;
$this->size = 0;
}
public function get($index){
if ($index>=$this->size || $index<0) return false;
$node = $this->head;
for ($i=0;$i<$index;$i++){
$node = $node->next;
}
return $node;
}
public function insert($data, $index=''){
$index = $index ? $index : $this->size;
if ($index>$this->size || $index<0) return false;
$new_node = new Node($data);
if ($index==0) {
$this->head = $new_node;
}elseif ($index==$this->size){
$this->get($this->size-1)->next = &$new_node;
}else{
$next_node = $this->get($index);
$this->get($index-1)->next = &$new_node;
$new_node->next = &$next_node;
}
$this->size++;
return true;
}
public function update($data, $index){
if ($index>=$this->size || $index<0) return false;
$this->get($index-1)->data = $data;
return true;
}
public function delete($index){
if ($index>=$this->size || $index<0) return false;
if ($index==0){
$this->head = $this->get(1);
}elseif ($index==$this->size-1){
$this->get($index-1)->next = null;
}else{
//$this->get($index-1)->next = &$this->get($index+1);
$per_node = $this->get($index-1);
$next_node = $per_node->next->next;
$per_node->next = &$next_node;
}
$this->size--;
return true;
}
}
class Node{
public $data;
public $next;
public function __construct($data){
$this->data = $data;
}
}
$list = new Singlelist();
$list->insert(2);
$list->insert(5);
$list->insert(6);
$list->insert(7);
$list->insert(8);
$list->insert(9);
var_dump($list->get(2)->data);
结果输出6