栈与队列操作注意:
栈(Stack):push,pop,top,isEmpty
队列(Queue):add,pop,peek,isEmpty
1 232. 用栈实现队列
题目: 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
思路: 用栈实现队列需要两个栈,一个实现输入,一个实现输出。
注意:实现输出时要特别注意,当接收到出队指令时,要判断出栈中是否还有元素,如果有直接出栈;如果没有则需要将入栈中的所有元素读入出栈中。
Java实现
class MyQueue {
// 定义两个栈实现队列功能
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>(); // 负责进队
stackOut = new Stack<>(); // 负责出队
}
// 模拟实现进队,实际进栈
public void push(int x) {
stackIn.push(x);
}
// 模拟实现出队,需要分类讨论出栈的情况
public int pop() {
dumpstackIn();
return stackOut.pop();
}
// 模拟实现取队首元素,和出队类似
public int peek() {
dumpstackIn();
return stackOut.peek();
}
// 实现队列判空,出栈和进栈双栈均为空
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 出栈分类讨论,如果stackOut为空,则stackIn中全部元素进stacOut;如果不为空,则正常出栈
private void dumpstackIn(){
if(!stackOut.isEmpty())
return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
/**
* 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();
*/
2 225. 用队列实现栈
题目: 请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
注意:
- 你只能使用队列的标准操作 —— 也就是
push to back
、peek/pop from front
、size
和is empty
这些操作。 - 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
思路:栈即单口操作的队列,所以用一个队列模拟栈的操作。入队和入栈操作一致;出栈操作将队尾元素保持不变,前面各位依次出队并入队,此时原队尾元素到达队首,出队,其余元素位置不变;取栈顶元素值与出栈类似,取得队尾元素值后再入队。
Java实现
class MyStack {
// 用一个队列实现栈
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
// 模拟实现进栈,入队列即可
public void push(int x) {
queue.add(x);
}
// 模拟实现出栈,保留最后一位其余各位出队后入队,
public int pop() {
rePositon();
return queue.poll();
}
// 模拟实现取栈顶元素值,与出栈相似但不出队,取得值后再入队
public int top() {
rePositon();
int result = queue.poll();
queue.add(result);
return result;
}
// 判空直接判断队列状态即可
public boolean empty() {
return queue.isEmpty();
}
// 出栈循环
private void rePositon(){
int size = queue.size();
size--;
while(size-->0){
queue.add(queue.poll());
}
}
}
/**
* 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();
*/