<?php
class ArrayList{
private $list;
private $size;
public function __construct()
{
$this->list=array();
$this->size=0;
}
//初始化链表
public function InitList(){
$this->list=array();
$this->size=0;
}
//删除链表
public function destoryList(){
if (isset($this->list)){
unset($this->list);
$this->size=0;
}
}
//清空链表
public function clearList(){
if (isset($this->list)){
unset($this->list);
}
$this->list=array();
$this->size=0;
}
//判断链表是否为空
public function emptyList(){
if (isset($this->list)){
if ($this->size==0){
return true;
}else{
return false;
}
}
}
//链表长度
public function lengthList(){
if (isset($this->list)){
return $this->size;
}else{
return false;
}
}
//取元素
public function getElem($i){
if ($i<1||$i>$this->size){
die('failed');
}
if (isset($this->list)&&is_array($this->list)){
return $this->list[$i-1];
}
}
//是否在链表中
public function locateElem($e){
if (isset($this->list)&&is_array($this->list)){
for ($i=0;$i<$this->size;$i++){
if ($this->list[$i]==$e){
return $i+1;
}
return 0;
}
}
}
//前驱
public function priorElem($i){
if ($i<1||$i>$this->size){
die('failed');
}
if ($i==1){
die('no prior');
}
if (isset($this->list)&&is_array($this->list)){
return $this->list[$i-2];
}
}
//后继
public function nextElem($i){
if ($i<1||$i>$this->size){
die('failed');
}
if ($i==$this->size){
die('no next');
}
if (isset($this->list)&&is_array($this->list)){
return $this->list[$i];
}
}
//插入元素
public function insertList($i,$e){
if ($i<1||$i>$this->size){
die('failed');
}
if (isset($this->list)&&is_array($this->list)){
if ($this->size==0){
$this->list[0]=$e;
$this->size++;
}else{
for($j=$this->size-1;$j>=$i;$j--){
$this->list[$j]=$this->list[$j-1];
}
$this->list[$i-1]=$e;
$this->size++;
}
}
}
//删除元素
public function deleteList($i){
if ($i<1||$i>$this->size){
die('failed');
}
if (isset($this->list)&&is_array($this->list)){
if ($i==$this->size){
unset($this->list[$i-1]);
}else{
unset($this->list[$i-1]);
for ($j=$i;$j<$this->size;$j++){
$this->list[$j-1]=$this->list[$j];
}
}
$this->size--;
}
}
//遍历
public function printList(){
if (isset($this->list)&&is_array($this->list)){
foreach ($this->list as $value) {
echo $value.' ';
}
}
}
}
php实现数据结构线性表(顺序)
最新推荐文章于 2022-02-19 16:17:47 发布