Skip to content

Commit

Permalink
php 09_queue
Browse files Browse the repository at this point in the history
  • Loading branch information
Hkesd committed Oct 15, 2018
1 parent 0b6dd0a commit aefc810
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 2 deletions.
115 changes: 115 additions & 0 deletions php/09_queue/QueueOnLinkedList.php
Original file line number Diff line number Diff line change
@@ -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 changes: 29 additions & 0 deletions php/09_queue/main.php
Original file line number Diff line number Diff line change
@@ -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();
5 changes: 4 additions & 1 deletion php/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@
* findMiddleNode 求链表的中间结点

#### 08_stack
* 链栈实现
* 链栈实现

#### 09_stack
* 队列链表实现
3 changes: 2 additions & 1 deletion php/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/"
}
}
}

0 comments on commit aefc810

Please sign in to comment.