栈和队列的常见面试题-Java实现
一:实现一个特殊的栈,在基本功能的基础上,再实现返回栈中最小元素的功能。
popElem、pushElem、getMinElem操作的时间复杂度都是O(1)。
public static class MyStack{
private static Stack<Integer> stackData;
private static Stack<Integer> stackMin;
public MyStack() {
stackData = new Stack<>();
stackMin = new Stack<>();
}
public int getMinElem(){
if (stackMin.isEmpty()){
System.out.println("栈为空!!");
}
return stackMin.peek();
}
public void pushElem(int newNum){
if (stackMin.isEmpty()){
stackMin.push(newNum);
}else if (newNum < getMinElem()){
stackMin.push(newNum);
}else {
stackMin.push(stackMin.peek());
}
stackData.push(newNum);
}
public int popElem(){
stackMin.pop();
return stackData.pop();
}
}
二:如何只用栈结构实现队列结构
从stackPush栈导数据到stackPop栈的规则
(1)stackPop栈为空
(2)导数据时,stackPush栈需一次性导出完
public static class TwoStacksQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<>();
stackPop = new Stack<>();
}
//stackPush栈向stackPop栈中导入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
}
public void add(int newNum) {
stackPush.push(newNum);
pushToPop();
}
public int poll() {
if (stackPush.empty() && stackPop.empty()) {
System.out.println("队列为空!!");
}
pushToPop();
return stackPop.pop();
}
public int peek() {
if (stackPush.empty() && stackPop.empty()) {
System.out.println("队列为空!!");
}
pushToPop();
return stackPop.peek();
}
}
三:如何只用队列结构实现栈结构
public static class TwoQueueStack<T> {
public Queue<T> queue;
public Queue<T> help;
public TwoQueueStack() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(T value) {
queue.offer(value);
}
public T poll() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public T peek() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
help.offer(ans);
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}