<?php
/*
* 类名:LNode
* 功能:线性表的链式存储实现
* @author xxy
*/
ini_set('display_errors',1);
error_reporting(E_ALL);
class Node {
public $key = null;
public $data = null; //存储数据元素
public $next = null; //存储下一个数据元素的地址
}
class LinkList{
private $head = null;
private $end = null;
public function insert($key, $data){
$node = new Node();
$node->key = $key;
$node->data = $data;
if($this->end==null){
$this->end = $node;
}else{
$this->end->next = $node;
$this->end = $node;
}
if ($this->head == null){
$this->head = $node;
}
return $node;
}
public function del_node($key){
$node = $this->head;
//echo $node; exit;
$pre_node = null;
while ( $node != null ){
if ($node->key == $key){
if($pre_node == null ){
$this->head = $node->next;
//$this->end;
if ($this->end == $node){
$this->end = null;
}
}else{
$pre_node->next = $node->next;
}
break;
}
$pre_node = $node;
$node = $node->next;
}
}
public function select($key){
$node = $this->head;
//echo $node; exit;
$pre_node = null;
while ( $node != null ){
if ($node->key == $key){
$node_data = $node->head->data;
break;
}else{
$pre_node = $node;
$node = $node->next;
}
}
return $node_data;
}
}
function test_link_insert_end(){
$link = new LinkList();
$info = array();
for($i=1;$i<5;$i++) {
$link->insert($i, $i);
}
return $link;
}
$link = test_link_insert_end();
print_r($link);
$s = $link->select(2);
$s = $link->del_node(3);
print_r($link);
print_r($s);
?>
php线性表小例子
最新推荐文章于 2022-02-19 16:17:47 发布