From 51f768c7899e72fe67ffa49aa15d5dc104cb0f9e Mon Sep 17 00:00:00 2001 From: Jensen Li <703448556@qq.com> Date: Sat, 1 Jun 2019 21:45:25 +0800 Subject: [PATCH] =?UTF-8?q?php=E5=AE=9E=E7=8E=B0=E8=B7=B3=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- php/17_skiplist/skipList.php | 108 +++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 php/17_skiplist/skipList.php diff --git a/php/17_skiplist/skipList.php b/php/17_skiplist/skipList.php new file mode 100644 index 0000000..dc08717 --- /dev/null +++ b/php/17_skiplist/skipList.php @@ -0,0 +1,108 @@ +data = $data; + } + + //获取当前节点索引层数 + public function getMaxLevel() + { + return count($this->next) - 1; + } +} + +class SkipList +{ + //索引最大层数 + public $indexLevel; + + //头节点 + protected $head; + + public function __construct(int $indexLevel) + { + $this->indexLevel = max($indexLevel, 0); + $this->head = new SNode(); + } + + public function addData($data) + { + $newNode = new SNode($data); + for ($level = $this->getRandomLevel(), $node = $this->head; $level >= 0; $level--) { + while (isset($node->next[$level]) && $data < $node->next[$level]->data) { + $node = $node->next[$level]; + } + if (isset($node->next[$level])) { + $newNode->next[$level] = $node->next[$level]; + } + $node->next[$level] = $newNode; + } + return $newNode; + } + + public function deleteData($data) + { + $deleted = false; + for ($level = $this->head->getMaxLevel(), $node = $this->head; $level >= 0; $level--) { + while (isset($node->next[$level]) && $data < $node->next[$level]->data) { + $node = $node->next[$level]; + } + if (isset($node->next[$level]) && $data == $node->next[$level]->data) { + $node->next[$level] = isset($node->next[$level]->next[$level]) ? + $node->next[$level]->next[$level] : null; + $deleted = true; + } + } + return $deleted; + } + + public function findData($data) + { + for ($level = $this->head->getMaxLevel(), $node = $this->head; $level >= 0; $level--) { + while (isset($node->next[$level]) && $data < $node->next[$level]->data) { + $node = $node->next[$level]; + } + if (isset($node->next[$level]) && $data == $node->next[$level]->data) { + return $node->next[$level]; + } + } + return false; + } + + protected function getRandomLevel() + { + return mt_rand(0, $this->indexLevel); + } +} + +/** + * 示例 + */ + +$indexLevel = 2; + +$skipList = new SkipList($indexLevel); + +for ($i = 10; $i >= 0; $i--) { + $skipList->addData($i); +} + +//打印0到10组成的跳表 +var_dump($skipList); + +//返回SNode对象 +var_dump($skipList->findData(5)); + +$skipList->deleteData(5); + +//返回false +var_dump($skipList->findData(5)); \ No newline at end of file