用队列实现栈

来源:3-2 作业解析:用队列实现栈

慕移动4606623

2021-04-27 14:35:28

问题描述:

老师你好,我是这样考虑的,在元素入栈的时候,因为队列是先进先出,而栈是先进后出,所以为了维护栈的进出顺序,所以在push()方法中,我先将需要进栈的元素x放入队列中,然后再将除了x之外的所有元素出队列,然后再入队列。这样就保证了栈的先进后出的顺序。然后直接将pop()方法定义为

queue.remove();

下面是我的实现代码

相关代码:

class MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}

/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for (int i = queue.size(); i >1 ; i--) {
queue.add(queue.poll());
}
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.remove();
}

/** Get the top element. */
public int top() {
queue.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}


写回答

2回答

假蛙工程师

2021-10-29

这不就是老师的第4种实现方式吗。嘿嘿,还是说你问问题的时候老师没有添加第4种实现方式

0

liuyubobobo

2021-04-27

赞!没有问题。


top 函数要写一个返回:return queue.peek()


继续加油!:)

0

算法与数据结构

波波老师5年集大成之作,算法与数据结构系统学习,考试、面试、竞赛通用

2603 学习 · 1086 问题

查看课程