題目地址:
https://www.lintcode.com/problem/implement-stack-by-two-queues/description
用兩個隊列來實現棧。
開兩個隊列和,其中作輔助用。push的時候直接向裏添加即可。pop和top的時候,要先將中除了最後一個元素以外的元素都poll出來並加入,然後取出僅剩的那個元素,再將兩個隊列引用交換。如果是pop的話,交換前要將的那個元素也poll出來,如果是top的話,交換前要將那個元素進。代碼如下:
import java.util.ArrayDeque;
import java.util.Queue;
public class Stack {
Queue<Integer> q1 = new ArrayDeque<>(), q2 = new ArrayDeque<>();
/*
* @param x: An integer
* @return: nothing
*/
public void push(int x) {
// write your code here
q1.offer(x);
}
/*
* @return: nothing
*/
public void pop() {
// write your code here
while (q1.size() > 1) {
q2.offer(q1.poll());
}
q1.poll();
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
/*
* @return: An integer
*/
public int top() {
// write your code here
while (q1.size() > 1) {
q2.offer(q1.poll());
}
int res = q1.peek();
q2.offer(q1.poll());
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
return res;
}
/*
* @return: True if the stack is empty
*/
public boolean isEmpty() {
// write your code here
return q1.isEmpty();
}
}
push時間複雜度,pop和top時間複雜度,爲已經在隊列裏的元素個數。空間。