後進先出 (LIFO):最後壓入的元素最先彈出。核心操作:push(入棧)、pop(出棧)、top(查看頂部)。
| 操作 | PHP 函數 | 說明 |
|---|---|---|
| push | array_push($stack, $val) | 返回新長度 |
| pop | array_pop($stack) | 返回彈出值,空棧返回 null |
| top | end($stack) 或 $stack[count($stack)-1] | 不移除 |
| isEmpty | empty($stack) | |
| size | count($stack) |
<?php
class Stack {
private array $data = [];
public function push(mixed $value): int { return array_push($this->data, $value); }
public function pop(): mixed { return array_pop($this->data); }
public function top(): mixed { return $this->data[array_key_last($this->data)] ?? null; }
public function isEmpty(): bool { return empty($this->data); }
public function size(): int { return count($this->data); }
public function toArray(): array { return $this->data; }
public function clear(): void { $this->data = []; }
}
// 使用
$stack = new Stack();
$stack->push('WEB');
$stack->push('PHP');
$stack->push('WWW.CHHUA.COM');
print_r($stack->toArray()); // ['WEB', 'PHP', 'WWW.CHHUA.COM']
echo $stack->pop(); // WWW.CHHUA.COM
print_r($stack->toArray()); // ['WEB', 'PHP']
array_push/pop 在末尾操作為 O(1) 擴攤。count(),緩存長度或用 $stack->size()。SplStack(C 實現,略快且嚴格 LIFO)。