這篇文章主要介紹了php鏈表用法,實例分析了php創建鏈表及針對鏈表節點的增加、刪除、更新與遍歷等常用操作,需要的朋友可以參考下
本文實例講述了php鏈表用法。分享給大家供大家參考。具體如下:
這里簡單介紹了php鏈表的基本用法,包括鏈表節點的創建、遍歷、更新等操作。
- <?php
- /**
- * @author MzXy
- * @copyright 2011
- * @param PHP鏈表
- */
- /**
- *
- *節點類
- */
- class Node
- {
- private $Data;//節點數據
- private $Next;//下一節點
- public function setData($value){
- $this->Data=$value;
- }
- public function setNext($value){
- $this->Next=$value;
- }
- public function getData(){
- return $this->Data;
- }
- public function getNext(){
- return $this->Next;
- }
- public function __construct($data,$next){
- $this->setData($data);
- $this->setNext($next);
- }
- }//功能類
- class LinkList
- {
- private $header;//頭節點
- private $size;//長度
- public function getSize(){
- $i=0;
- $node=$this->header;
- while($node->getNext()!=null)
- { $i++;
- $node=$node->getNext();
- }
- return $i;
- }
- public function setHeader($value){
- $this->header=$value;
- }
- public function getHeader(){
- return $this->header;
- }
- public function __construct(){
- header("content-type:text/html; charset=utf-8");
- $this->setHeader(new Node(null,null));
- }
- /**
- *@author MzXy
- *@param $data--要添加節點的數據
- *
- */
- public function add($data)
- {
- $node=$this->header;
- while($node->getNext()!=null)
- {
- $node=$node->getNext();
- }
- $node->setNext(new Node($data,null));
- }
- /**
- *@author MzXy
- *@param $data--要移除節點的數據
- *
- */
- public function removeAt($data)
- {
- $node=$this->header;
- while($node->getData()!=$data)
- {
- $node=$node->getNext();
- }
- $node->setNext($node->getNext());
- $node->setData($node->getNext()->getData());
- }
- /**
- *@author MzXy
- *@param 遍歷
- *
- */
- public function get()
- {
- $node=$this->header;
- if($node->getNext()==null){
- print("數據集為空!");
- return;
- }
- while($node->getNext()!=null)
- {
- print($node->getNext()->getData());
- if($node->getNext()->getNext()==null){break;}
- $node=$node->getNext();
- }
- }
- /**
- *@author MzXy
- *@param $data--要訪問的節點的數據
- * @param 此方法只是演示不具有實際意義
- *
- */
- public function getAt($data)
- {
- $node=$this->header->getNext();
- if($node->getNext()==null){
- print("數據集為空!");
- return;
- }
- while($node->getData()!=$data)
- {
- if($node->getNext()==null){break;}
- $node=$node->getNext();
- }
- return $node->getData();
- }
- /**
- *@author MzXy
- *@param $value--需要更新的節點的原數據 --$initial---更新后的數據
- *
- */
- public function update($initial,$value)
- {
- $node=$this->header->getNext();
- if($node->getNext()==null){
- print("數據集為空!");
- return;
- }
- while($node->getData()!=$data)
- {
- if($node->getNext()==null){break;}
- $node=$node->getNext();
- }
- $node->setData($initial);
- }
- }
- ?>
希望本文所述對大家的php程序設計有所幫助。
新聞熱點
疑難解答