<?phpphp
class Node{node
private $_data;this
private $_next = null;spa
private $_pre = null;three
function __construct($data){get
$this->_data = $data;it
}io
function getData(){function
return $this->_data;class
}
function getNext(){
return $this->_next;
}
function setData($data){
$this->_data = $data;
}
function setNext(Node $next){
$this->_next = $next;
}
function getPre(){
return $this->_pre;
}
function setPre(Node $pre){
$this->_pre = $pre;
}
}
class LinkList{
private $_head = null;
private $_tail = null;
private $_size = 0;
function __construct($data){
$this->addNode($data);
}
function addNode($data,$flag=0){
if($this->_size > 0){
$node = new Node($data);
if($flag==0){
$node->setNext($this->_head);
$this->_head->setPre($node);
$this->_head = $node;
}else{
$this->_tail->setNext($node);
$node->setPre($this->_tail);
$this->_tail = $node;
}
}else{
$this->_tail = $this->_head = new Node($data);
}
++$this->_size;
}
function findNodeByPos($pos,&$node)
{
if($pos == 0 || $pos == -$this->_size)
return $this->_head;
$k = abs($pos);
if($k > $this->_size-1)
return null;
$node = ($pos>0?$this->_head->getNext():$this->_tail);
for($i=1;$i<$k;$i++){
if($pos>0)
$node = $node->getNext();
else
$node = $node->getPre();
}
}
function insertNode($data,$pos = 0){
if($pos == 0)
$this->addNode($data);
else if($pos >= $this->_size)
$this->addNode($data,1);
else {
$this->findNodeByPos($pos-1,$node);
$newNode = new Node($data);
$newNode->setNext($node->getNext());
$newNode->setPre($node);
$node->getNext()->setPre($newNode);
$node->setNext($newNode);
++$this->_size;
}
}
function delNode($data){
$node = $this->_head;
if($node->getData() == $data){
$this->_head = $note->getNext();
$this->_head->setPre(null);
--$this->_size;
return true;
}
for($i=1;$i<$this->_size;$i++){
if($node->getNext()->getData() == $data){
$node->getNext()->getNext()->setPre($note);
$node->setNext($node->getNext()->getNext());
break;
}
$node = $node->getNext();
}
if($i < $this->_size){
--$this->_size;
if($i == $this->_size-1){
$this->_tail = $node;
}
return true;
}
return false;
}
function iterate($flag=0){
if($flag == 0){
$node = $this->_head;
for($i=0;$i<$this->_size;$i++){
echo 'data:',$node->getData(),'<br/>';
$node = $node->getNext();
}
}else{
$node = $this->_tail;
for($i=0;$i<$this->_size;$i++){
echo 'data:',$node->getData(),'<br/>';
$node = $node->getPre();
}
}
}
function getSize(){
return $this->_size;
}
}
$link = new LinkList('one');
$link->addNode('two');
$link->addNode('three');
$link->addNode('zero',1);
$link->insertNode('four',2);
$link->iterate(1);