Merge pull request #65 from Hkesd/master

php 09_queue
This commit is contained in:
wangzheng0822 2018-10-16 10:44:43 +08:00 committed by GitHub
commit af53eaca05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 150 additions and 2 deletions

View File

@ -0,0 +1,115 @@
<?php
/**
* User: Hkesd
* Date: 2018/10/13 11:26
* Desc:
*/
namespace Algo_09;
use Algo_06\SingleLinkedListNode;
/**
* 队列 链表实现
*
* Class QueueOnLinkedList
*/
class QueueOnLinkedList
{
/**
* 队列头节点
*
* @var SingleLinkedListNode
*/
public $head;
/**
* 队列尾节点
*
* @var null
*/
public $tail;
/**
* 队列长度
*
* @var int
*/
public $length;
/**
* QueueOnLinkedList constructor.
*/
public function __construct()
{
$this->head = new SingleLinkedListNode();
$this->tail = $this->head;
$this->length = 0;
}
/**
* 入队
*
* @param $data
*/
public function enqueue($data)
{
$newNode = new SingleLinkedListNode();
$newNode->data = $data;
$this->tail->next = $newNode;
$this->tail = $newNode;
$this->length++;
}
/**
* 出队
*
* @return SingleLinkedListNode|bool|null
*/
public function dequeue()
{
if (0 == $this->length) {
return false;
}
$node = $this->head->next;
$this->head->next = $this->head->next->next;
$this->length--;
return $node;
}
/**
* 获取队列长度
*
* @return int
*/
public function getLength()
{
return $this->length;
}
/**
* 打印队列
*/
public function printSelf()
{
if (0 == $this->length) {
echo 'empty queue' . PHP_EOL;
return;
}
echo 'head.next -> ';
$curNode = $this->head;
while ($curNode->next) {
echo $curNode->next->data . ' -> ';
$curNode = $curNode->next;
}
echo 'NULL' . PHP_EOL;
}
}

29
php/09_queue/main.php Normal file
View File

@ -0,0 +1,29 @@
<?php
/**
* User: Hkesd
* Date: 2018/10/13 11:46
* Desc:
*/
namespace Algo_09;
require_once "../vendor/autoload.php";
$queue = new QueueOnLinkedList();
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
$queue->enqueue(4);
$queue->enqueue(5);
$queue->printSelf();
var_dump($queue->getLength());
$queue->dequeue();
$queue->printSelf();
$queue->dequeue();
$queue->dequeue();
$queue->dequeue();
$queue->printSelf();
$queue->dequeue();
$queue->printSelf();

View File

@ -18,3 +18,6 @@
#### 08_stack
* 链栈实现
#### 09_stack
* 队列链表实现

View File

@ -7,7 +7,8 @@
"psr-4": {
"Algo_06\\": "06_linkedlist/",
"Algo_07\\": "07_linkedlist/",
"Algo_08\\": "08_stack/"
"Algo_08\\": "08_stack/",
"Algo_09\\": "09_queue/"
}
}
}