PHP 双向队列

答案

  1. /**
  2. * 双向队列PHP版
  3. */
  4. class DoubleEndedQueue
  5. {
  6. private $queue = [];
  7. public function addHead($item)
  8. {
  9. return array_unshift($this->queue, $item);
  10. }
  11. public function addTail($item)
  12. {
  13. return array_push($this->queue, $item);
  14. }
  15. public function removeHead()
  16. {
  17. return array_shift($this->queue);
  18. }
  19. public function removeTail()
  20. {
  21. return array_pop($this->queue);
  22. }
  23. public function getAll()
  24. {
  25. return $this->queue;
  26. }
  27. public function isEmpty()
  28. {
  29. return empty($this->queue);
  30. }
  31. }

答案解析

测试代码:

  1. $q = new DoubleEndedQueue();
  2. $q->addHead('php'); // $q->queue = ['php']
  3. $q->addTail('java'); // $q->queue = ['php', 'java']
  4. $q->addHead('python'); // $q->queue = ['python','php', 'java']
  5. print_r($q->getAll());
  6. var_dump($q->isEmpty());
  7. $q->removeHead(); // $q->queue is: ['php', 'java']
  8. $q->removeTail(); // $q->queue is: ['php']
  9. $q->removeHead(); // $q->queue is: []
  10. print_r($q->getAll());
  11. var_dump($q->isEmpty());