php实现链表的基本操作


<?php  

class node{
    private $value;
    private $next;
    public function __construct($value=0,$next=null){
        $this->value=$value;
        $this->next=$next;
    }
    public function getValue(){
        return $this->value;
    }
    public function setValue($value){
        return $this->value=$value;
    }
    public function getNext(){
        return $this->next;
    }
    public function setNext($next){
        return $this->next=$next;
    }
}
function reverse($node){
    if (null == $node || null == $node->getNext()) {
        return $node;
    }
    $reversednode = reverse($node->getNext());
    $node->getNext()->setNext($node);
    $node->setNext(null);
    return $reversednode;
}
function insert($node,$value,$position){
    $tmp=$node;
    for($i=0;$i<$position;$i++){
        $tmp=$tmp->getNext();
    }
    $insertnode=new node($value);
    $insertnode->setNext($tmp->getNext());
    $tmp->setNext($insertnode);
}
function delete($node,$position){
    $tmp=$node;
    for($i=0;$i<$position;$i++){
        $tmp=$tmp->getNext();
    }
    $tmp->setNext($tmp->getNext()->getNext());
}
echo "<pre>";
$node=new node();
$tmp=$node;
for($i=1;$i<10;$i++){
    $nextnode=new node($i);
    $tmp->setNext($nextnode);
    $tmp=$nextnode;
}
print_r($node);
$node=reverse($node);
insert($node,11,3);
delete($node,3);
print_r($node);
?>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM