SplStack

SplStack extends SplDoublyLinkedList implements Iterator, Countable, ArrayAccess, Serializable

SPL 提供的双向链表栈(LIFO),push/pop 在两端均为 O(1)。

C C23

C23
#include <stdio.h>

#define CAP 8

// C 无内置栈:数组 + 栈顶下标手写惯用法
static char *stack[CAP];
static int top = -1;

static void push(char *s) { stack[++top] = s; }
static const char *pop(void) { return stack[top--]; }
static const char *peek(void) { return stack[top]; }

int main(void) {
    push("a");
    push("b");
    push("c");
    printf("pop: %s\n", pop());
    printf("top: %s\n", peek());
    printf("count: %d\n", top + 1);
    // 自底向顶遍历:直接按下标访问
    printf("bottom to top: %s,%s\n", stack[0], stack[1]);
    return 0;
}
输出
pop: c
top: b
count: 2
bottom to top: a,b

C++ C++26

C++26
#include <iostream>
#include <stack>
#include <string>
#include <vector>

int main() {
    // std::stack 容器适配器(默认基于 deque):push/pop/top 均 O(1)
    std::stack<std::string> stack;
    stack.push("a");
    stack.push("b");
    stack.push("c");
    std::cout << "pop: " << stack.top() << "\n";
    stack.pop();
    std::cout << "top: " << stack.top() << "\n";
    std::cout << "count: " << stack.size() << "\n";
    // std::stack 不可遍历:倒进 vector 再反向还原自底向顶
    std::vector<std::string> rest;
    while (!stack.empty()) {
        rest.push_back(stack.top());
        stack.pop();
    }
    std::cout << "bottom to top: ";
    for (auto it = rest.rbegin(); it != rest.rend(); ++it) {
        std::cout << (it != rest.rbegin() ? "," : "") << *it;
    }
    std::cout << "\n";
    return 0;
}
输出
pop: c
top: b
count: 2
bottom to top: a,b

C# v11.0.100

v11.0.100
using System.Collections.Generic;
using System.Linq;

// Stack<T> 泛型栈:Push/Pop/Peek 均 O(1)
var stack = new Stack<string>();
stack.Push("a");
stack.Push("b");
stack.Push("c");
Console.WriteLine("pop: " + stack.Pop());
Console.WriteLine("top: " + stack.Peek());
Console.WriteLine("count: " + stack.Count);
// 枚举顺序自顶向下:Reverse 得自底向顶
Console.WriteLine("bottom to top: " + string.Join(",", stack.Reverse()));
输出
pop: c
top: b
count: 2
bottom to top: a,b

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Go 无内置栈:切片 append/尾部截断惯用法(需要语义 API 时手写薄包装)
	var stack []string
	stack = append(stack, "a", "b", "c")
	// 弹出末尾元素
	top := stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Println("pop:", top)
	fmt.Println("top:", stack[len(stack)-1])
	fmt.Println("count:", len(stack))
	fmt.Println("bottom to top:", strings.Join(stack, ","))
}
输出
pop: c
top: b
count: 2
bottom to top: a,b

Java v27.0.1

v27.0.1
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        // 官方推荐 ArrayDeque 而非遗留 Stack 类(继承 Vector 带锁):push/pop 均 O(1)
        Deque<String> stack = new ArrayDeque<>();
        stack.push("a");
        stack.push("b");
        stack.push("c");
        System.out.println("pop: " + stack.pop());
        System.out.println("top: " + stack.peek());
        System.out.println("count: " + stack.size());
        // 迭代自顶向下:descendingIterator 反向得自底向顶
        Iterator<String> it = stack.descendingIterator();
        StringBuilder rest = new StringBuilder();
        while (it.hasNext()) {
            if (rest.length() > 0) rest.append(",");
            rest.append(it.next());
        }
        System.out.println("bottom to top: " + rest);
    }
}
输出
pop: c
top: b
count: 2
bottom to top: a,b

JavaScript v26.13.1

v26.13.1
// JS 惯用数组当栈:push/pop 都是尾部操作
const stack = [];
stack.push("a");
stack.push("b");
stack.push("c");
console.log("pop: " + stack.pop());
console.log("top: " + stack.at(-1));
console.log("count: " + stack.length);
console.log("bottom to top: " + stack.join(","));
输出
pop: c
top: b
count: 2
bottom to top: a,b

PHP v8.6.0

v8.6.0
// SplStack:双向链表实现的栈,push/pop 两端均 O(1)
$stack = new SplStack();
$stack->push("a");
$stack->push("b");
$stack->push("c");
echo "pop: ", $stack->pop(), "\n";
echo "top: ", $stack->top(), "\n";
echo "count: ", $stack->count(), "\n";
// 迭代固定自顶向下(LIFO 模式冻结不可改):反转得自底向顶
echo "bottom to top: ", implode(",", array_reverse(iterator_to_array($stack)));
输出
pop: c
top: b
count: 2
bottom to top: a,b

Python v3.15.2

v3.15.2
# Python 无专用栈类:list append/pop(-1) 惯用法(尾部 O(1),自带方法无需包装)
stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print("pop: " + stack.pop())
print("top: " + stack[-1])
print("count: " + str(len(stack)))
# 列表迭代自底向顶,与栈底到栈顶一致
print("bottom to top: " + ",".join(stack))
输出
pop: c
top: b
count: 2
bottom to top: a,b

Rust v1.99.1

v1.99.1
fn main() {
    // Vec 即栈惯用法:push/pop 尾部 O(1)(双端需求用 VecDeque)
    let mut stack: Vec<&str> = Vec::new();
    stack.push("a");
    stack.push("b");
    stack.push("c");
    println!("pop: {}", stack.pop().unwrap());
    println!("top: {}", stack.last().unwrap());
    println!("count: {}", stack.len());
    // Vec 迭代自底向顶
    println!("bottom to top: {}", stack.join(","));
}
输出
pop: c
top: b
count: 2
bottom to top: a,b

TypeScript v26.13.1

v26.13.1
// 栈惯用法:数组 push/pop
const stack: string[] = [];
stack.push("a");
stack.push("b");
stack.push("c");
console.log("pop: " + stack.pop());
console.log("top: " + stack.at(-1));
console.log("count: " + stack.length);
console.log("bottom to top: " + stack.join(","));
输出
pop: c
top: b
count: 2
bottom to top: a,b

语言差异说明

C:手写数组+栈顶下标是标配;动态容量需 realloc 或链表——SplStack 解决的正是容量与实现细节的封装。

C++:std::stack 是容器适配器(默认 deque);语言已有栈,PHP 引入 SPL 是给数组文化补 OO 语义。

C#:Stack<T> 泛型栈(循环数组实现);与 SplStack 同为集合类栈,但 .NET 从 1.0 就有。

Go:无内置栈——切片尾部 append/截断即惯用法,需要语义化 API 时手写薄包装。

Java:遗留 Stack 类继承 Vector(带锁、设计过时),官方 javadoc 明确推荐 ArrayDeque。

JavaScript:数组 push/pop 天然是栈操作,语言文化从不觉得缺一个栈类。

PHP:数组底层是哈希桶+双向链表:array_push/array_pop 尾部摊还 O(1) 可用,但 array_shift/array_unshift 头部是 O(n);SplStack 用双向链表让两端 O(1)、语义清晰(top/bottom/isEmpty/count),并支持序列化。历史:SPL 随 PHP 5.0 引入、5.3 转正,是"面向对象更专业"年代的产物——现代 PHP 数组当栈依然高效,SplStack 的价值更多在明确意图与 OO 接口(Countable/Iterator/ArrayAccess)。

Python:list 自带栈语义(append/pop),无需专门类;官方文档直接把列表标为栈实现。

Rust:Vec push/pop 即栈(双端需求用 VecDeque);所有权模型让"借栈"边界更明确。

TypeScript:同 JavaScript——数组即栈。