php标准库(spl)
栈:先进后出,后进先出
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
$q->push(4);
$q->add(4,5);
$q->rewind();
while(
$q->valid()){
echo
$q->current(),"\n";
$q->next();
}
?>
Output
5
4
3
2
1
队列:先进先出,后进后出
$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');
$queue->rewind();
while(
$queue->valid()){
echo
$queue->current(),"\n";
$queue->next();
}
print_r($queue);
$queue->dequeue(); //remove first one
print_r($queue);
?>
Output
A
B
C
SplQueue Object
(
[flags:SplDoublyLinkedList:private] => 4
[dllist:SplDoublyLinkedList:private] => Array
(
[0] => A
[1] => B
[2] => C
)
)
SplQueue Object
(
[flags:SplDoublyLinkedList:private] => 4
[dllist:SplDoublyLinkedList:private] => Array
(
[0] => B
[1] => C
)
)
小顶堆: 堆的每个父节点都小于孩子节点
$h = new SplMinHeap();
// [parent, child]
$h->insert([9, 11]);
$h->insert([0, 1]);
$h->insert([1, 2]);
$h->insert([1, 3]);
$h->insert([1, 4]);
$h->insert([1, 5]);
$h->insert([3, 6]);
$h->insert([2, 7]);
$h->insert([3, 8]);
$h->insert([5, 9]);
$h->insert([9, 10]);
for (
$h->top(); $h->valid(); $h->next()) {
list(
$parentId, $myId) = $h->current();
echo
"$myId ($parentId)\n";
}
固定长度数组:
$array = new SplFixedArray(5);
$array[1] = 2;
$array[4] = "foo";
var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)
var_dump($array["4"]); // string(3) "foo"
网友评论