用栈实现队列(Java) 您所在的位置:网站首页 舆论对司法的积极影响 用栈实现队列(Java)

用栈实现队列(Java)

2023-10-08 02:50| 来源: 网络整理| 查看: 265

用栈实现队列 在这里插入图片描述 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返回队列开头的元素 boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

题解:双队列,一个作为输入栈,一个作为输出栈 Tips:注意栈是先入后出,而队列是先入先出,所以对于删除和查看对头元素要特别注意,将栈中元素整个反转到另一个栈中进行操作

class MyQueue { private Stack a; //输入栈 private Stack b; //输出栈 /** * Initialize your data structure here. */ public MyQueue() { a = new Stack(); b = new Stack(); } /** * Push element x to the back of queue. */ public void push(Integer x) { a.push(x); } /** * Removes the element from in front of queue and returns that element. */ public Integer pop() { //如果 b 为空,则将 a 中的元素压入 b 中 if (b.isEmpty()) { while (!a.isEmpty()) { b.push(a.pop()); } } return b.pop(); } /** * Get the front element. */ public Integer peek() { if (b.isEmpty()) { while (!a.isEmpty()) { b.push(a.pop()); } } return b.peek(); } /** * Returns whether the queue is empty. */ public boolean empty() { return a.isEmpty() && b.isEmpty(); } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有