Home > php教程 > php手册 > body text

php线性表顺序存储实现代码(增删查改)

WBOY
Release: 2016-06-06 20:40:11
Original
1208 people have browsed it

php实现线性表顺序存储的代码,需要的朋友可以参考下

代码如下:
/*
*文件名:linearList.php
* 功能:数据结构线性表的顺序存储实现
* author:黎锦焕
* @copyright:www.drw1314.com
*/
class linearList {
private $arr;
private $length;
const MAXSIZE=100;
/*
*构造函数,判断空表还是飞空表,并且进行实例化
* @param array $arr 输入的数组
* @param int $n 输入数组的长度
* @ruturn void;
*/
function __construct($arr,$n) {
if($n>self::MAXSIZE) {
echo '对不起,数组的长度'.$n.'超出了内存空间!'.self::MAXSIZE;
} else if($necho '异常,长度不能为负数。';
} else if($n==0) {
echo '
....你创建了一张空表,数组长度为0....

';
$this->arr=$arr;
$this->length=$n;
}else{
echo '
....成功创建一张表....

';
$this->arr=$arr;
$this->length=$n;
}
}
/*
*按位查找,返回查找到的值
* @ruturn string;
* @param int $n 查找的位置
*/
function findValue($n) {
if($n>$this->length||$nreturn '输入的位置'.$n.'不正确,请在1到'.$this->length.'的范围内';
}
return '你要找的第'.$n.'位的值为'.$this->arr[$n-1];
}
/*
*按值查找,返回查找到的位置
* @ruturn string;
* @param int $n 查找的值
*/
function findSite($n) {
for($i=0;$ilength;$i++){
if($this->arr[$i]==$n){
$b=$i+1;
return '你要找的值'.$n.'对应的位置为'.$b;
}else{
$v=false;
}
}
if(!$v){
return '你所找的值'.$n.'不存在';
}
}
/*
*在选定的位置处插入某个值
* @ruturn array;
* @param int $i 插入位置
* @param int $v 插入的值
*/
function insertValue($i,$v) {
if($iself::MAXSIZE){
echo '插入的位置'.$i.'不正确,请在1到'.self::MAXSIZE.'的范围内';
return ;
}
for($h=$this->length;$h>=$i;$h--){
$this->arr[$h]=$this->arr[$h-1];
}
if($i>$this->length){
$this->arr[$this->length]=$v;
}else{
$this->arr[$i-1]=$v;
}
$this->length++;
return $this->arr;
}
/*
*在选定的位置删除某个值
* @ruturn array;
* @param int $i 位置
*/
function deleteValue($i) {
if($i$this->length){
echo '选定的位置'.$i.'不正确,请在1到'.$this->length.'的范围内';
return ;
}
for($j=$i;$jlength;$j++){
$this->arr[$j-1]=$this->arr[$j];
}
unset($this->arr[$this->length-1]);
$this->length--;
return $this->arr;
}
function __destruct(){
if($this->length==0){
echo '
...销毁一张空表...
';
}else{
echo '
...成功销毁一张表..
';
}
}
}
//下面是使用案例
$arr=array(10,125,123,1,4);
$n=5;
$linearList=new linearList($arr, $n);
echo $linearList->findValue(5).'
';
echo $linearList->findSite(4).'
';
echo '
'; <br>print_r($linearList->insertValue(20,300)); <br>echo '
Copy after login
';
echo '
'; <br>print_r($linearList->deleteValue(1)); <br>echo '
Copy after login
';
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!