PHP單鏈表

<?phpphp

class Node{node

private $_data;this

private $_next = null;spa

function __construct($data){three

$this->_data = $data;get

}it


function getData(){io

   return $this->_data;function

}class


function getNext(){

   return $this->_next;

}


function setData($data){

   $this->_data = $data;

}


function setNext(Node $next){

   $this->_next = $next;

}

}


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 = $node;

  }else{

               $this->_tail->setNext($node);

  $this->_tail = $node;

  }

  }else{

           $this->_tail = $this->_head = new Node($data);

  }

  ++$this->_size;

}


function findNodeByPos($pos,&$node)

{

if($pos>$this->_size-1 || $pos < 0)

return null;

        $node = $this->_head;

for($i=0;$i<$pos;$i++){

$node = $node->getNext();

}

}


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());

             $node->setNext($newNode);

            

++$this->_size;

}

}


function delNode($data){

        $node = $this->_head;

if($node->getData() == $data){

            $this->_head = $note->getNext();

--$this->_size;

return true;

}

for($i=1;$i<$this->_size;$i++){

if($node->getNext()->getData() == $data){

   $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(){

$node = $this->_head;

for($i=0;$i<$this->_size;$i++){

   echo 'data:',$node->getData(),'<br/>';

$node = $node->getNext();

}

}


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();

//print_r($link);

相關文章
相關標籤/搜索