使用隊列實現棧的下列操作:
push(x) – 元素 x 入棧
pop() – 移除棧頂元素
top() – 獲取棧頂元素
empty() – 返回棧是否爲空
注意:
1.你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
2.你所使用的語言也許不支持隊列。 你可以使用 list 或者deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
3.你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。
JAVA
思路:
棧:先進後出
隊列:先進先出
用隊列實現棧,需要創建兩個隊列,分別爲q1,q2
(1).入棧:實際將元素放到底層的隊列中,將元素入隊列到q1中。
(2).移除棧頂元素:
①.將q1中size-1個元素移到q2中;
②.從q1中取棧頂元素;
③.交換q1和q2;
(3).獲取棧頂元素:
①.將q1中size-1個元素移到q2中;
②.從q1中取棧頂元素;
③.將q1中的一個元素搬移到q2中;→ q2.offer(q1.poll());
④.交換q1和q2;
(4).判空: 判斷q1是不是空
代碼如下:
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
//1、將q1中的size-1個元素搬到q2中
while(q1.size() > 1){
q2.offer(q1.poll()); // q1中的siza-1個元素出隊列 然後在進隊列q2中
}
//2、刪除q1中的隊頭元素
int ret=q1.poll();
//3、交換q1 q2
Queue<Integer> temp= q1;
q1=q2;
q2=temp;
return ret;
}
/** Get the top element. */
public int top() {
//1、將q1中的size-1個元素搬到q2中
while(q1.size() > 1){
q2.offer(q1.poll()); // q1中的siza-1個元素出隊列 然後在進隊列q2中
}
//2、獲取q1中的隊頭元素
int ret=q1.peek();
q2.offer(q1.poll());
//3、交換q1 q2
Queue<Integer> temp= q1;
q1=q2;
q2=temp;
return ret;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}