什麼是單向鏈表node
鏈表是以鏈式存儲數據的結構,其不須要連續的存儲空間,鏈表中的數據以節點來表示,每一個節點由元素(存儲數據)和指針(指向後繼節點)組成。segmentfault
單向鏈表(也叫單鏈表)是鏈表中最簡單的一種形式,每一個節點只包含一個元素和一個指針。
它有一個表頭,而且除了最後一個節點外,全部節點都有其後繼節點。
它的存儲結構以下圖所示
函數
代碼實現this
定義節點指針
class Node { public $data; /** * @var null | Node */ public $next; public function __construct($data) { $this->data = $data; $this->next = null; } }
單鏈表實現code
/** * 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; } } }
示例blog
$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();
來源:https://segmentfault.com/a/1190000017764793圖片