leetcode刷题之栈相关
- q232 用栈实现队列
题目描述:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty)
我们知道,栈的性质是先进后出,队列的性质是先入先出。如果仅仅有一个栈,数据依次进栈,依次出栈,先进去的后出来。使用两个栈,可以让一个实现进,一个实现出。即:第一个栈进数据,然后依次出,按照出的顺序再进到第二个栈,然后第二个栈的数据出栈,这样可以实现数据的先进先出,即队列的相关功能。
class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
//定义两个栈,用于实现队列的相关功能
s1=new Stack<Integer>();
s2=new Stack<Integer>();
}
/** Push element x to the back of queue. */
//数据进队列,则是进第一个栈
public void push(int x) {
s1.push(x);
}
//数据出队列,因为要实现先进先出,把第一个栈进去的数据,全部弹出,放到第二个栈,再把第二个栈的数据弹出
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(s2.isEmpty()){
while(!s1.empty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
//返回队列开头元素
/** Get the front element. */
public int peek() {
if(s2.isEmpty()){
while(!s1.empty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
//判断相关栈是否为空
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty()&&s2.isEmpty();
}
}
- q225 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
官方给出了两种方法,来看一下先用一个队列实现的。
队列先进先出,那如何让后进的实现先出呢?关键在于,如何让后进的数据排在队列的头部。为了让后进的数据排在队列的头部,我们每次进数据时,都把队列中已有的数据出队,再让后进数据进队。这样输出时,就能保证后进先出,也就是实现了栈的功能。
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue= new LinkedList<>();
}
//实现入栈功能时,相当于把后面的数据顶到了最前面
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
//将之前的全部都出队,然后再入队,注意这里i的初始值为1
for(int i = 1;i<queue.size();i++){
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
最后总结一下:
定义一个栈:Stack
定义一个队列:Queue

浙公网安备 33010602011771号