行业知识
LeetCode 0225.用队列实现栈:基础数据结构的学习
2026-11-07 09:40:43
来源:互联网转载
【LetMeFly】225.用队列实现栈:基础数据结构的学习
力���题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
()请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
()- void push(int x) 将元素 x 压入栈顶。
- int pop() 移除并返回栈顶元素。
- int top() 返回栈顶元素。
- boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
- 你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
- 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:["MyStack", "push", "push", "top", "pop", "empty"][[], [1], [2], [], [], []]输出:[null, null, null, 2, 2, false]解释:MyStack myStack = new MyStack();myStack.push(1);myStack.push(2);myStack.top(); // 返回 2myStack.pop(); // 返回 2myStack.empty(); // 返回 False
提示:
- 1 private: queue } void push(int x) { queue tempQ.push(q.front()); q.pop(); } swap(q, tempQ); } int pop() { int ans = q.front(); q.pop(); return ans; } int top() { return q.front(); } bool empty() { return q.empty(); }};h5Python/h5 pre # from collections import dequeclass MyStack: def __init__(self): self.q = deque() def push(self, x: int) - None: temp = deque() temp.append(x) while self.q: temp.append(self.q.popleft()) self.q = temp def pop(self) -> int: return self.q.popleft() def top(self) -> int: return self.q[0] def empty(self) -> bool: return not self.q
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/136429312
- 1 private: queue } void push(int x) { queue tempQ.push(q.front()); q.pop(); } swap(q, tempQ); } int pop() { int ans = q.front(); q.pop(); return ans; } int top() { return q.front(); } bool empty() { return q.empty(); }};h5Python/h5 pre # from collections import dequeclass MyStack: def __init__(self): self.q = deque() def push(self, x: int) - None: temp = deque() temp.append(x) while self.q: temp.append(self.q.popleft()) self.q = temp def pop(self) -> int: return self.q.popleft() def top(self) -> int: return self.q[0] def empty(self) -> bool: return not self.q
上一篇:服务器配置怎么确认的啊?