本篇文章給大家分享的是有關php中怎么實現數據結構的單向鏈表,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
代碼實現
定義節點
class Node
{
public $data;
/**
* @var null | Node
*/
public $next;
public function __construct($data)
{
$this->data = $data;
$this->next = null;
}
}單鏈表實現
/**
* Class SingleLinkList
* 單鏈接的實現示例,實現簡單的填加,插入,刪除, 查詢,長度,遍歷這幾個簡單操作
*/
class SingleLinkList
{
/**
* 鏈表頭結點,頭節點必須存在,
* @var Node
*/
public $header;
private $size = 0;
/**
* 構造函數,默認填加一個哨兵節點,該節點元素為空
* SingleLinkList constructor.
*/
public function __construct()
{
$this->header = new Node(null);
}
/**
* 在鏈表末尾添加節點
* @param Node $node
* @return int
*/
public function addNode(Node $node)
{
$current = $this->header;
while ($current->next != null) {
$current = $current->next;
}
$current->next = $node;
return ++$this->size;
}
/**
* 在指定位置插入節點
* @param int $index 節點位置,從1開始計數
* @param Node $node
* @return int
* @throws Exception
*/
public function insertNodeByIndex($index, Node $node)
{
if ($index < 1 || $index > ($this->size + 1)) {
throw new Exception(sprintf('你要插入的位置,超過了鏈表的長度 %d', $this->size));
}
$current = $this->header;
$tempIndex = 1;
do {
if ($index == $tempIndex++) {
$node->next = $current->next;
$current->next = $node;
break;
}
} while ($current->next != null && ($current = $current->next));
return ++$this->size;
}
/**
* 刪除節點
* @param int $index 節點位置,從1開始計數
* @return int
* @throws Exception
*/
public function deleteNodeByIndex($index)
{
if ($index < 1 || $index > ($this->size + 1)) {
throw new Exception('你刪除的節點不存在');
}
$current = $this->header;
$tempIndex = 1;
do {
if ($index == $tempIndex++) {
$current->next = $current->next->next;
break;
}
} while ($current->next != null && ($current = $current->next));
return --$this->size;
}
/**
* 查詢節點
* @param int $index 節點位置,從1開始計數
* @return Node|null
* @throws Exception
*/
public function searchNodeByIndex($index) {
if ($index < 1 || $index > ($this->size + 1)) {
throw new Exception('你查詢的節點不存在');
}
$current = $this->header;
$tempIndex = 1;
do {
if ($index == $tempIndex++) {
return $current->next;
}
} while ($current->next != null && ($current = $current->next));
}
/**
* 獲取節點長度
* @return int
*/
public function getLength()
{
return $this->size;
}
/**
* 遍歷列表
*/
public function showNode()
{
$current = $this->header;
$index = 1;
while ($current->next != null) {
$current = $current->next;
echo 'index --- ' . $index++ . ' --- ';
echo var_export($current->data);
echo PHP_EOL;
}
}
}示例
$link = new SingleLinkList(); $link->addNode(new Node(1)); $link->addNode(new Node(2)); $link->insertNodeByIndex(3, new Node(3)); $link->addNode(new Node(4)); $link->addNode(new Node(5)); echo $link->getLength(), PHP_EOL; $link->showNode(); echo '-----------', PHP_EOL; var_dump($link->searchNodeByIndex(3)); echo '-----------', PHP_EOL; $link->deleteNodeByIndex(3); $link->showNode();
以上就是php中怎么實現數據結構的單向鏈表,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。