# Python示例
stack = []
stack.append(5) # 入栈(Push)
top = stack[-1] # 查看栈顶(Peek)
stack.pop() # 出栈(Pop)
// Java示例
Queue queue = new LinkedList<>();
queue.offer(10); // 入队(Enqueue)
int front = queue.peek(); // 查看队首
queue.poll(); // 出队(Dequeue)
// C语言实现
#define SIZE 100
int queue[SIZE];
int front = 0, rear = 0;
void enqueue(int val) {
if ((rear + 1) % SIZE == front) return; // 队满
queue[rear] = val;
rear = (rear + 1) % SIZE;
}
// JavaScript实现
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
}
}
def isValid(s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
// 阶乘递归示例
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n-1); // 每次调用创建新栈帧
}
def levelOrder(root):
if not root: return []
queue = deque([root])
res = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(level)
return res
使用双端队列实现LRU算法:
class LRUCache {
private LinkedHashMap cache;
private int capacity;
public LRUCache(int capacity) {
this.cache = new LinkedHashMap<>(capacity, 0.75f, true);
this.capacity = capacity;
}
public int get(int key) {
return cache.getOrDefault(key, -1);
}
public void put(int key, int value) {
if (cache.size() >= capacity && !cache.containsKey(key)) {
Iterator it = cache.keySet().iterator();
it.next();
it.remove();
}
cache.put(key, value);
}
}
栈溢出:
空栈操作:
// 错误示例
stack s;
s.pop(); // 未检查空栈直接pop会导致运行时错误
循环队列的满队条件:
(rear + 1) % size == front
rear == front
(会导致无法区分空队和满队)操作 | Python (列表) | Java (LinkedList) | C++ (deque) |
---|---|---|---|
入栈/入队 | O(1)* | O(1) | O(1) |
出栈 | O(1) | O(1) | O(1) |
出队 | O(n) | O(1) | O(1) |
随机访问 | O(1) | O(n) | O(1) |
(*Python列表在动态扩容时会有O(n)复杂度,但均摊分析仍为O(1)) |