【发布时间】:2023-03-04 21:37:01
【问题描述】:
在 PHP 中有两种方法可以将数组用作 堆栈 (LIFO)
以及将它们用作队列 (FIFO) 的两种方式。
可以使用push 和pop 实现堆栈,
但是unshift & shift 也可以做到这一点。
同样可以使用push 和shift 实现队列,
但是unshift & pop 也可以做到这一点。
演示:
echo "stack push & pop approach:\n";
$s = []; array_push($s, 'first'); array_push($s, 'second'); array_push($s, 'third');
echo array_pop($s) . '-' . array_pop($s) . '-' . array_pop($s) . "\n";
echo "stack unshift & shift approach:\n";
$s = []; array_unshift($s, 'first'); array_unshift($s, 'second'); array_unshift($s, 'third');
echo array_shift($s) . '-' . array_shift($s) . '-' . array_shift($s) . "\n";
echo "queue push & shift approach:\n";
$q = []; array_push($q, 'first'); array_push($q, 'second'); array_push($q, 'third');
echo array_shift($q) . '-' . array_shift($q) . '-' . array_shift($q) . "\n";
echo "queue unshift & pop approach:\n";
$q = []; array_unshift($q, 'first'); array_unshift($q, 'second'); array_unshift($q, 'third');
echo array_pop($q) . '-' . array_pop($q) . '-' . array_pop($q) . "\n";
哪些输出:
stack push & pop approach:
third-second-first
stack unshift & shift approach:
third-second-first
queue push & shift approach:
first-second-third
queue unshift & pop approach:
first-second-third
那么使用哪组函数呢?!
【问题讨论】: