最近一直在忙一些個人的私事,導(dǎo)致好多計劃都中斷了。說多了都是借口,歸根結(jié)底是自己沒有規(guī)劃好時間,堅持做下去,下面回正題繼續(xù)做題。
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
思路:
一、自己的第一個思路是用兩個queue和一個變量top,一個queue專門負(fù)責(zé)存push進(jìn)來的元素,一個queue負(fù)責(zé)在pop的時候臨時存放push queue中前n-1個元素,top用來存當(dāng)前最后一個push進(jìn)來的元素。
在pop的時候,需要先把push queue前n-1個元素移動到pop queue,把push queue最后一個元素remove以后,再把push queue和pop queue交換。
二、在solution里看到第三種方法十分巧妙,用一個queue就可以實現(xiàn)。每次push把元素添加到隊列以后,就把隊列前n-1個元素重新入隊。下面以依次push 1到4為例:
1-->1,2-->2,1-->2,1,3-->3,2,1-->3,2,1,4-->4,3,2,1
可以看到每次push元素后,隊列就變成了相應(yīng)的stack表達(dá)。
下面發(fā)一下第二種方法的代碼:
public class HA_StackByQueue {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public HA_StackByQueue() {
this.queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
this.queue.offer(x);
int size = this.queue.size();
while (size > 1) {
this.queue.offer(this.queue.poll());
size--;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return this.queue.poll();
}
/** Get the top element. */
public int top() {
return this.queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return this.queue.isEmpty();
}
}