栈实现队列解题思路
-
队列具备的属性是先进先出,栈具备属性是先进后出,因此如果要用栈实现队列,那就需要考虑用两个栈来实现元素出队,入队。
-
这两个栈中的元素和就是推入进来的所有元素。
栈实现队列解题代码
import java.util.Stack;
/**
* @description:
* @author: lilang
* @version:
* @modified By:[email protected]
*/
public class StackToQueue {
private Stack<Integer> stack;
private Stack<Integer> stack2;
public StackToQueue() {
stack = new Stack();
stack2 = new Stack<>();
}
/**
* 添加元素到队尾
*/
public void push(int x) {
stack.push(x);
}
/**
* 删除队头的元素并返回
*/
public int pop() {
peek();
if (stack2.isEmpty()) {
return -1;
}
return stack2.pop();
}
/**
* 返回队头元素
*/
public int peek() {
/**
* 这步判断尤其重要,这是决定两个栈的元素个数之和等于推入的所有元素个数之后
*/
if (stack2.isEmpty()) {
while (!stack.isEmpty()) {
stack2.push(stack.pop());
}
}
if (!stack2.isEmpty()) {
return stack2.peek();
}
return -1;
}
/**
* 判断队列是否为空
*/
public boolean empty() {
return stack2.isEmpty() && stack.isEmpty();
}
}
队列实现栈
该实现方式很简单,代码如下:
/**
* @description:
* @author: lilang
* @version:
* @modified By:[email protected]
*/
public class QueueToStack {
private LinkedList<Integer> queue;
public QueueToStack() {
queue = new LinkedList<Integer>();
}
/**
* 添加元素到栈顶
*/
public void push(int x) {
queue.offerLast(x);
}
/**
* 删除栈顶的元素并返回
*/
public int pop() {
return queue.pollLast();
}
/**
* 返回栈顶元素
*/
public int top() {
return queue.peekLast();
}
/**
* 判断栈是否为空
*/
public boolean empty() {
return queue.isEmpty();
}
}