Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

数据结构 – php版顺序表

2019-11-18 22:13:41

<?php

class sequenceList {
	public $L;
	public $maxsize = 0;
	public $length = 0;
	
	function __construct($size){
		$this->L = array();
		$this->maxsize = $size;
	}
	
	/* 
	 * @return void
	 */
	function __destruct(){
		$this->destroy();
	}
	
	function destroy(){
		foreach ($this->L as $key => $value){
			unset($this->L[$key]);
		}
	}
	
	/* 
	 * @return bool
	 * @param $item: String
	 * @param $index: int
	 */
	function insertList($item, $index){
		if ($index < 1 || $index > $this->length + 1) {
			return false;
		}
		
		if ($this->length == $this->maxsize) {
			return false;
		}
		
		for ($i = $this->length; $i > $index - 1; $i--){
			$this->L[$i] = $this->L[$i-1];
		}
		
		$this->L[$index-1] = $item;
		$this->length += 1;
		return true;
		
	}
	
	function deleteList($index){
		if ($index < 1 || $index > $this->length){
			return false;
		}
		
		if ($this->length == 0) {
			return false;
		}

		for ($i = $index - 1; $i < $this->length; $i++) {
			if ($i == $this->length-1){
				unset($this->L[$i]);
			} else {
				$this->L[$i] = $this->L[$i + 1];
			}
		}
		
		$this->length -= 1;
		return true;
		
	}
	
	function printList(){
		print_r($this->L);
	}
	
	/*
	 * @return bool
	 */
	function isEmpty(){
		if ($this->length == 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/* 
	 * @return string
	 */
	function getElem($index){
		if ($index < 1 || $index > $this->length){
			return "unvalid index $index, which should be within [1, $this->length]";
		}
		return $this->L[$index-1];
	}
	
	/* 
	 * @return int
	 */
	function locateElem($ele){
		for ($i = 0; $i < $this->length; $i++){
	
			if ($this->L[$i] == $ele) {
				return $i + 1;
			}
		} 
		return -1;
	}
	
	/* 
	 * @return int
	 */
	function getLength(){
		return count($this->L);
	}
	
	function getPriorEle(){
		
	}
	
	function getLateEle(){
		
	}
}


$a = new sequenceList(8);
$a->printList();

$a->insertList("helo", 1);
$a->insertList('morning',2);
$a->insertList('evening', 3);
$a->insertList('kk', 4);
$a->insertList('pp', 2);
$a->insertList('ok', 4);

$a->deleteList(3);
$a->printList();

echo $a->length.'<br>';
echo $a->locateElem('evening').'<br>';
echo $a->getElem(5).'<br>';
var_dump($a->isEmpty());
echo $a->length.'<br>';
echo $a->getLength().'<br>';
$a->destroy();
$a->printList();


?>

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *