232. Implement Queue using Stacks
225. Implement Stack using Queues
今天这俩差不多,主要是看对STACK的FILO和QUEUE的FIFO的理解,做法也差不多,就合在一起写了
无论是232 还是 225都可以用 一个STACK/QUEUE的思想来解决,就是在push里利用该数据结构的特性整理一下,满足之后pop以及peek的需求
232 由于要implement的是FIFO的 QUEUE,所以在每次push的时候,把stack里的数据全push到一个临时stack中,最后把新加进来的数push进去,然后再把temp的数全push到原stack中,这样stack刚好是倒序,可以直接pop peek符合queue的情况
225也是类似,由于implement FILO的stack,也就是说新加进来的数要整理后放在queue的首位,于是每次push之后,把新加进去的数之前的数全queue.add(queue.remove())到后面即可,由于QUEUE的特性
//232. Implement Queue using Stacks
Stack<Integer> stack;
public MyQueue() {
stack = new Stack<>();
}
public void push(int x) {
Stack<Integer> temp = new Stack<>();
while(!stack.isEmpty()){
temp.push(stack.pop());
}
temp.push(x);
while(!temp.isEmpty()){
stack.push(temp.pop());
}
}
public int pop() {
return stack.pop();
}
public int peek() {
return stack.peek();
}
public boolean empty() {
return stack.isEmpty() ? true : false;
}
}
// 225. Implement Stack using Queues
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
for(int i = 0; i< queue.size() -1 ; i++ ){
queue.add(queue.remove());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty() ? true: false;
}
}
,这里不需要申请临时queue