这两个数据结构设计类问题在我的文章 栈,队列,矩阵相关基础题目及答案 中已经有详细的解析了~
用队列实现栈题解:
本题思路如下:
用两个队列来实现栈这种结构,当向自己设计的栈结构push数据的时候,其中一个队列正常进行入队操作。当需要我们pop数据的时候,将有数据的那个队列除去队末的那个数字都enqueue(入队)到另一个队列中,并且让指向两个队列的引用交换。代码如下:
class MyStack {
private Queue<Integer> dataQueue;
private Queue<Integer> helpQueue;
/** Initialize your data structure here. */
public MyStack() {
this.dataQueue = new LinkedList<>();
this.helpQueue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
dataQueue.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(dataQueue.isEmpty()){
throw new RuntimeException("stack is empty");
}
while(dataQueue.size() != 1){
helpQueue.add(dataQueue.poll());
}
int res = dataQueue.poll();
Queue<Integer> tmp = dataQueue;
dataQueue = helpQueue;
helpQueue = tmp;
return res;
}
/** Get the top element. */
public int top() {
if(dataQueue.isEmpty()){
throw new RuntimeException("stack is empty");
}
while(dataQueue.size() != 1){
helpQueue.add(dataQueue.poll());
}
int res = dataQueue.poll();
Queue<Integer> tmp = dataQueue;
dataQueue = helpQueue;
helpQueue = tmp;
dataQueue.add(res);
return res;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return dataQueue.isEmpty() && helpQueue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
代码执行结果如下:
用栈实现队列题解:
使用两个栈来实现一个队列结构,其中一个栈为dataStack,另一个为helpStack。当队列发生进队操作时,向dataStack里push数据,当队列发生出队操作时,如果helpStack为空,就将dataStack依次pop出的数据push进helpStack中,然后返回helpStack pop的数据,如果helpStack不为空,就直接返回helpStack pop的数据,代码如下:
class MyQueue {
private Stack<Integer> dataStack;
private Stack<Integer> helpStack;
/** Initialize your data structure here. */
public MyQueue() {
this.dataStack = new Stack<>();
this.helpStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
dataStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(dataStack.isEmpty() && helpStack.isEmpty()){
throw new RuntimeException("queue is empty");
}
if(helpStack.isEmpty()){
while(!dataStack.isEmpty()){
helpStack.push(dataStack.pop());
}
}
return helpStack.pop();
}
/** Get the front element. */
public int peek() {
if(dataStack.isEmpty() && helpStack.isEmpty()){
throw new RuntimeException("queue is empty");
}
if(helpStack.isEmpty()){
while(!dataStack.isEmpty()){
helpStack.push(dataStack.pop());
}
}
return helpStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return dataStack.isEmpty() && helpStack.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
代码执行结果:
网友评论