リニア・テーブル-チェーン・ストレージ構造(phpバージョン)
3293 ワード
<?php
/**
* @desc
* ,
* :
* 1. ,
* 2. ,
* 3. ( ), ( )
* 4. , $i , , O(n),
*
* 5.
* :
*
* :
*
* @author ranping 2012-08-19
*/
class LinkList {
private $headNode; // , : delete(1), headNode
public function __construct(){
$this->initLink();
}
public function initLink() {
$this->headNode = new Node(); //
}
/**
* @desc
* $i O(n)
* @param int $i
*/
public function getElem($i) {
$j = 1;//
$node = $this->headNode->getNext();
while( $node && $j < $i) {
$node = $node->getNext();
++$j;
}
if(!$node || $j > $i) { //$i
return false;
}
$data = $node->getData(); // $i
return $data;
}
/**
* $desc
* $i $data O(n)
* ($data ), O(n), O(1)
* @param int $i
* @param $data
*/
public function insert($i, $data) {
$j = 1; //
$node = $this->headNode; //
while($node && $j < $i) {
$node = $node->getNext();
++ $j;
}
if(!$node || $j > $i) { // $i
return false;
}
$newNode = new Node();
$newNode->setData($data);
$newNode->setNext($node->getNext());
$node->setNext($newNode);
return true;
}
/**
* @desc
* $i
* $headNode 1 ,
* O(n)
*
* $i , , O(n), O(1)
* : , , 10 delete() O(n), 。
* , , delete() , ,
* @param int $i
*/
public function delete($i) {
$j = 1;
$node = $this->headNode; //
while($node && $j<$i) {
$node = $node->getNext();
++ $j;
}
if(!$node || $j>$i) {
return false;
}
$delNode = $node->getNext(); //
$node->setNext($delNode->getNext());//
unset($delNode); //
return true;
}
}
/**
* @desc
*
*
* @author ranping 2012-08-19
*/
class Node {
private $data; //
private $next; //
public function getData() {
return $this->data;
}
public function getNext() {
return $this->next;
}
public function setData($data) {
$this->data = $data;
}
public function setNext($next) {
$this->next = $next;
}
}
$list = new LinkList();
$list->insert(1, 1);
$list->insert(2, 2);
$list->insert(3, 3);
$list->insert(4, 4);
print_r($list);
echo '<hr/>';
$list->delete(3);
print_r($list);