php實現單鏈表(靜態鏈表)
data = $data; $next && $this->next = $next; } public function getData(){ return $this->data; } public function setData($data){ $this->data = $data; } public function getNext(){ return $this->next; } public function setNext($next){ $this->next = $next; } } //單鏈表類 class LinkList{ private $data_list = NULL; //結點集 public function LinkList($data = false){ $this->data_list = array(); $title = new Node(NULL); $this->data_list[] = $title; if($data){ if(is_array($data)){ $this->addMoreData($data); }else{ $this->addData($data); } } } //返回第N個結點的值 public function getNodeByNumber($number){ return $this->data_list[$this->findKeyByNumber($number)]->getData(); } //添加一組結點 public function addMoreData($datas){ foreach($datas as $value){ $this->addData($value); } } //添加結點統一入口,供外面調用 //$number 添加在第幾個結點的後面 public function addData($data, $number = false){ $node = new Node($data); if($number === FALSE || $number == count($this->data_list)){ $this->insertLastNode($node); }elseif($number > count($this->data_list)){ return false; }else{ $this->insertNode($node, $number); } } //插入一個結點到最後 private function insertLastNode($node){ $node->setNext(NULL); $lastKey = $this->findLastNode(); $insert_key = $this->insertNodeIntoArray($node); $this->data_list[$lastKey]->setNext($insert_key); } //插入一個結點 private function insertNode($node, $number){ $insert_number = $this->findKeyByNumber($number); $node->setNext($this->data_list[$insert_number]->getNext()); $insert_key = $this->insertNodeIntoArray($node); $this->data_list[$insert_number]->setNext($insert_key); } //尋找第N個結點對應的數組key private function findKeyByNumber($number){ $i = $key = 0; while($i < $number){ $key = $this->data_list[$key]->getNext(); $i ++; } return $key; } //將結點加入數組 private function insertNodeIntoArray($node){ $this->data_list[] = $node; return $this->getLastKey(); } //刪除結點 public function deleteNode($number){ if($number == 0 || $number > count($this->data_list)){ return false; } $pre_key = $this->findKeyByNumber($number - 1); $key = $this->data_list[$pre_key]->getNext(); $this->data_list[$pre_key]->setNext($this->data_list[$key]->getNext()); unset($this->data_list[$key]); } //尋找某結點的前一個結點 private function getPreNodeKey($key){ foreach($this->data_list as $k=>$v){ if($v->getNext() == $key){ return $k; } } return false; } //列印鏈表 public function getData_list(){ return $this->data_list; } //返回數組的最後一個鍵 private function getLastKey(){ end($this->data_list); return key($this->data_list); } //判斷某個索引值是否存在 private function ifExistKey($key){ if(array_key_exists($key, $this->data_list)){ return true; } return false; } //尋找尾結點 public function findLastNode(){ foreach($this->data_list as $key=>$value){ if($value->getNext() === NULL){ return $key; } } } }?>